<?php if( ! defined('BASEPATH')) exit('No direct script access allowed');
/* ************************************************** *\
 * @company		: NovaITech							  *	
 * @author		: van.vo@novaitech.com				  * 
 * @copyright	: 2012								  * 
 * ================================================== *
 * @date		: 04/26/2012
 * @project		: Drag & Drop
 * @description	: 
 *		- 
 *
\* ************************************************** */

class Transaction extends MY_Controller{
    function __construct( ){
        parent::__construct( );  
		$this->load->helper( array( 'form', 'url' ) );
		$this->load->model( 'CodeGenerator_model', '', TRUE );
		$this->load->helper('date');
    }
	
	function index(){
	    $this->giaodich();
		/*
		$this->load_template();
		$this->data[ 'custom_error' ] = '';
		$username = "noname";
		$userid = 0;
		//die($this->input->post("muaphieu"));
		$Cust_ID = $this->uri->segment( 3 );
		$goto=false;
		if(empty($Cust_ID))
			$Cust_ID = $this->input->post('Cust_ID');
		else $goto = true;
        $khachhang = $this->input->post('khachhang');
        //$ee_id = $this->input->post('EE_ID');
        //$ee_name = $this->input->post('EE_Name');
        $stt = $this->input->post('stt');
        $bonus = $this->input->post('Bonus');
		if(empty($stt)) $stt =1;
		$this->data['Cust_ID'] = $Cust_ID;
		$this->data['khachhang'] = $khachhang;
		
		
		$this->data['stt'] = $stt;
        $Serv_ID = $this->input->post('Serv_ID');
		$sql = "select s.*, c.Name as Category_Name, Time from services as s, categories as c where s.Cat_ID=c.Ca_ID";
        $categories   =   $this->CodeGenerator_model->custom_query($sql, "array");
		$combobox_cats=array();
		foreach($categories as $cat){
			$combobox_cats['']="";
			if($cat['Time'])
				$combobox_cats[$cat['Serv_ID']]=$cat['Category_Name']."-".$cat['Serv_Name']." ".$cat['Time']."'";
			else
				$combobox_cats[$cat['Serv_ID']]=$cat['Category_Name']."-".$cat['Serv_Name'];
		}
		$combobox_cats_str = "";$ee_id="";$ee_name="";
		//xu ly phieu
		$sql = "select * from phieukh where Cust_ID ='$Cust_ID' and Active=1";
		$phieu = $this->CodeGenerator_model->custom_query($sql,"array");
		$dm_phieu['5'] = 'Phieu 5 suat - tang 1 xuat';
		$dm_phieu['10'] = 'Phieu 10 suat - tang 3 xuat';
		$combobox_phieu = form_dropdown('sosuat', $dm_phieu,"5");
		//phieu khach hang
		$cats_phieu=array();
		$cats_phieu[''] = "Them phieu";
		foreach($phieu as $itm){
			$cats_phieu[$itm['ID']] = "Phieu ".$itm['SoSuat']." suat - con lai ".$itm['Conlai']." suat";
		}
		
		for($i = 1; $i <= $stt; $i++){
			//xu ly 
			$selected_cat = $this->input->post('Serv_ID'.$i);
			$style="style='width: 140px; float: left; margin-left: 5px;' id='Serv_ID".$i."' class='services' onchange=\"service_change('Serv_ID".$i."');\"";
			if($i==1)
				$s = '<span class="required"><font color="red">*</font></span>';
			else $s='';
			$combobox_phieu = form_dropdown('sosuat'.$i, $dm_phieu,"5");
			$combobox_phieu_of_kh = form_dropdown('Phieu_ID'.$i, $cats_phieu,"");
			$combobox_cats_str .=$this->_cbService($combobox_cats,$selected_cat,$style,$i,$s,$combobox_phieu,$combobox_phieu_of_kh);
		}
		//$this->data['ee_id'] = $ee_id;
		//$this->data['ee_name'] = $ee_name;
		//get danh muc
		$selected_dm=$this->input->post('Cat_ID');
		if(empty($selected_dm)) $selected_dm =9;
		$categories=$this->CodeGenerator_model->get('categories','*');
		$combobox_dm=array();
		foreach($categories as $cat){
			$combobox_dm[$cat['Ca_ID']]=$cat['Name'];
		}
		$this->data['combobox_dm']=form_dropdown('dm_id', $combobox_dm,$selected_dm);
		
		$date_tmp = $this->input->post('Create_Dt');
		//lay tien tip
		if(!empty($date_tmp)) $ngay = str_replace(array("/"),array(""),$date_tmp);
		else $ngay= date("d",time()).date("m").date("Y",time());
		$tientip  =   $this->CodeGenerator_model->get( 'tientip', '*', 'Ngay = "' . $ngay . '"' );  
		if(empty($bonus) && !empty($tientip)) $this->data['Bonus']= $tientip[0]['Price'];
		else $this->data['Bonus']= $bonus;
		
		$this->data['combobox_cats']=$combobox_cats_str;
		$this->form_validation->set_message('required', 'Vui lòng điền thông tin %s.');
		//xu ly database
        if( $this->form_validation->run( 'transaction_add' ) == false ){
             $this->data[ 'custom_error' ] = ( validation_errors( ) ? '<div class="form_error">' . validation_errors( ) . '</div>' : false );
        }else{   
			//xu ly trung
			// $Phieu_ID = substr($Phieu_ID, 0, -3);
			// $Serv_ID = substr($Serv_ID, 0, -3);
			$create_dt = $date_tmp;
			if(empty($create_dt))$create_dt = time();
			else $create_dt = strtotime(str_replace(array("/"),array("."),$create_dt));
		
            $data = array(
                    'Cust_ID' => $Cust_ID,
					//'Phieu_ID' =>$phieuid,
					//'Serv_ID' => $Serv_ID,
					'Serv_Name'=> "",
					'Promo_ID' => $this->xl_str_duplacate(set_value('Promo_ID'),";"),
					//'EE_ID' => $ee_id,
					//'EE_Name'=>substr($ee_name,0,-2),
					'Bonus' => 0,
					'Price' => set_value('Price'),
					'Discount_Percent' => set_value('Discount_Percent'),
					'Create_Dt' => $create_dt,
					'Money' => set_value('Money'),
					'Completed' => 1
            );
			
            $result = $this->CodeGenerator_model->add( 'transaction', $data, 'Tran_ID' ,true);
			if( $result > 0){				
				for($j=1;$j<=$stt;$j++){
					//them tien tip va phieu
					$isphieu = $this->input->post("muaphieu$j");
					$servid= $this->input->post("Serv_ID$j");
					$bonus = $this->input->post("tientip$j");
					$nguoitip = $this->input->post("EE_ID$j");
					$nguoitip = $this->xl_str_duplacate($nguoitip,",");
					$sosuat = $this->input->post("sosuat$j");					
					$gia = $this->input->post("gia$j");
					$giam = $this->input->post("giam$j");
					$thanhtien = $this->input->post("thanhtien$j");
					$percent_serv = $this->input->post("Percent_Serv$j");									
					$ghichu = $this->input->post("ghichu$j");									
					$conlai = $this->input->post("conlai$j");									
					if($isphieu){					
						//die($gia);
						$phieuid=$this->input->post("Phieu_ID$j"); //da co' phieu hay chua???
						if(!empty($phieuid)){ //co' roi thi' cap nhat lai
							$record_phieu   =   $this->CodeGenerator_model->get( 'phieukh', '*', 'ID = "' . $phieuid . '"', NULL, NULL, true );  
							if(!empty($record_phieu)){
								$Serv_ID = $record_phieu->Serv_ID;
								$conlai = $record_phieu->Conlai - 1;
								if($conlai==0) $active = 0; else $active = 1;
								$this->CodeGenerator_model->edit( 'phieukh', array('Active'=>0), 'ID',$phieuid); 								
								$arr_phieu=array(
									'Cust_ID'=>$record_phieu->Cust_ID,
									'Tran_ID'=>$result,
									//'EE_ID'=>$nguoitip,
									//'TienTip'=>$bonus,
									'Active' => $active,
									'SoSuat' =>$record_phieu->SoSuat,
									'Serv_ID' => $record_phieu->Serv_ID,
									'Giam' => $giam,
									//'Price_Serv' => $record_phieu->Price_Serv * $this->PercentService($nguoitip),
									'Gia' => 0,
									'Tang' => $record_phieu->Tang,
									'Conlai' =>$conlai,
									'GhiChu' =>$ghichu,
									'Create_Dt' => $create_dt
								);
								$arr = explode(",",$nguoitip);
								foreach($arr as $itm){
									if(!empty($itm)){
										$arr_phieu['EE_ID'] = $itm;
										$arr_phieu['TienTip'] = $bonus/count($arr);
										$arr_phieu['Price_Serv'] = $record_phieu->Price_Serv * $this->PercentService($itm);										
										$phieuid=$this->CodeGenerator_model->add("phieukh",$arr_phieu,$phieuid,true);
									}									
								}
							}
						}else {//chua co thi them	
							$service   =   $this->CodeGenerator_model->get( 'services', '*', 'Serv_ID = "' . $servid . '"', NULL, NULL, true );  	
							if($sosuat==5) $tang = 1;
							else $tang = 3;	
							
							//$price_serv = ($thanhtien/($sosuat+$tang) > 50 ? ($thanhtien/($sosuat+$tang) - 10):($thanhtien/($sosuat+$tang) - 5))*$service->Percent_Serv/100;	
// $str =$thanhtien." ". $price_serv . " ".($sosuat+$tang);
// $str = $service->Price." ".$giam." ".$service->Percent_Serv." ".$sosuat." ".$tang;
							$price_serv = ((($service->Price*(100-$giam)/100)*$sosuat)/($sosuat+$tang));
							// echo $price_serv;
							$price_serv = ($price_serv > 50 ? $price_serv - 10 : $price_serv - 5) * $service->Percent_Serv/100;
							$arr_phieu=array(
								'Cust_ID'=>$Cust_ID,
								'Tran_ID'=>$result,
								//'EE_ID'=>$nguoitip,
								//'TienTip'=>$bonus,
								'Active' => 1,
								'SoSuat' =>$sosuat,
								'Serv_ID' => $servid,
								'Giam' => $giam,
								'Gia' => $sosuat * $gia,
								//'Price_Serv' => $price_serv * $this->PercentService($nguoitip),
								'Tang' => $tang,
								'Conlai' =>$conlai,
								'GhiChu' =>$ghichu,
								'Create_Dt' =>$create_dt
							);
							$arr = explode(",",$nguoitip);
								foreach($arr as $itm){
									if(!empty($itm)){
										$arr_phieu['EE_ID'] = $itm;
										$arr_phieu['TienTip'] = $bonus/count($arr);
										$arr_phieu['Price_Serv'] = $price_serv * $this->PercentService($itm);
										$phieuid=$this->CodeGenerator_model->add("phieukh",$arr_phieu,$phieuid,true);
									}
							}
						}
					
					}else{
						$price_serv = ($gia > 50 ? ($gia - 10):($gia - 5))*$percent_serv/100;	
						$arr = explode(",",$nguoitip);
						$arr_tientip = array('Tran_ID'=>$result,'Ngay'=>$ngay,'Create_Dt'=>$create_dt,'Serv_ID'=>$servid,'GhiChu' =>$ghichu);
						foreach($arr as $itm){
							if(!empty($itm)){
								$arr_tientip['EE_ID'] =  $itm;
								$arr_tientip['Price'] = $bonus/count($arr);
								$arr_tientip['Price_Serv'] = $price_serv * $this->PercentService($itm);
								$this->CodeGenerator_model->add( 'tientip',$arr_tientip ,'ID' );  
							}
						}
					}				
					//end 	
				}	
				// echo $str;
				// die();
				redirect( base_url() . 'index.php/transaction/manage/' );
			}else{
				$this->data[ 'custom_error' ] = '<div class="form_error"><p>An Error Occured.</p></div>';
			}
		}	
		//xu ly goto
		if($goto){
			$customer   =   $this->CodeGenerator_model->get( 'customer', '*', 'Cust_ID = "' . $Cust_ID . '"', NULL, NULL, true );  
		}else $customer = array();
		
		$this->data['customer'] = $customer;
		$this->data['phieu'] = $phieu;
		
		$this->template->write( 'title', 'Spa - Thanh toan' );
        $this->template->write_view( 'content', 'transaction.php',$this->data );
        $this->template->render();
		/*
		$body = '';
		ob_start ();
		$this->load->view ( 'transaction_add', $this->data );
		$body = ob_get_clean ();
		echo $body;
		exit();
		*/
    } 
	// lay danh sach service
	function getListService(){
		
	}
	
	//xl giao dich
	function saveTran(){
		$ee_id = $this->input->post('ee_id');
		$gia = $this->input->post('gia');
		$giam = $this->input->post('giam');
		$tientip = $this->input->post('tientip');
		$ghichu = $this->input->post('ghichu');
		$id = $this->input->post('id');
		$phieu = $this->input->post('phieu');
		$service_id = $this->input->post('service_id');
		$box_new = $this->input->post('box_new');
		$box_tran_id = $this->input->post('box_tran_id');
		$thanhtien = $this->input->post('thanhtien');
		$cust_id = $this->input->post('cust_id');
		$create_dt = $this->input->post('create_dt');
		$box_percent_serv = $this->input->post('box_percent_serv');
		if(empty($create_dt))$create_dt = time();
		else $create_dt = strtotime(str_replace(array("/"),array("."),$create_dt));
		$date_tmp = $this->input->post('Create_Dt');

		if(!empty($date_tmp)) $ngay = str_replace(array("/"),array(""),$date_tmp);
		else $ngay= date("d",time()).date("m").date("Y",time());
		
		//xl giao dich
		if(empty($box_tran_id)){ // them giao dich moi
			$data = array(
						'Cust_ID' => $cust_id,
						//'Promo_ID' => $this->xl_str_duplacate(set_value('Promo_ID'),";"),
						'Bonus' => 0,
						'Price' => 0,
						'Discount_Percent' => 0,
						'Create_Dt' => $create_dt,
						'Money' => 0,
						'Completed' => 0
			  );
				
			 $box_tran_id = $this->CodeGenerator_model->add( 'transaction', $data, 'Tran_ID' ,true);			 
		}
		if($phieu) //la phieu
		{
			
		}else //ko la phieu
		{
			$price_serv = ($gia > 50 ? ($gia - 10):($gia - 5))*$box_percent_serv/100;
			
			$arr = $ee_id;
			$arr_tientip = array('Serv_ID'=>$service_id,'GhiChu' =>$ghichu);
			
			foreach($arr as $itm){
				if(!empty($itm)){
					$arr_tientip['EE_ID'] =  $itm;
					$arr_tientip['Price'] = $tientip/count($arr);
					$PercentService = $this->PercentService($itm);
					$arr_tientip['Price_Serv'] = $price_serv * $this->PercentService($itm);
					if(!$box_new) //edit
						$this->CodeGenerator_model->edit( 'tientip', $arr_tientip ,'ID',$id);
					else //add
					{
						$arr_tientip['Tran_ID'] = $box_tran_id;
						$arr_tientip['Ngay'] = $ngay;
						$arr_tientip['Create_Dt'] = $create_dt;
						$this->CodeGenerator_model->add( 'tientip',$arr_tientip ,'ID' );  
						//tinh lai thanh tien
						$result   =   $this->CodeGenerator_model->get( 'transaction', '*', 'Tran_ID = "' . $box_tran_id . '"', NULL, NULL, true );  
						$update=array(
								"Price"=>$result->Price + $gia,
								"Money"=>$result->Price + $thanhtien,
								"Discount_Percent"=>$result->Discount_Percent + $giam,
								"Completed"=>1
						);
						$this->CodeGenerator_model->edit( 'transaction', $update ,'Tran_ID',$box_tran_id);
					}
				}
			}
		}
		$data['result'] = $arr_tientip;
		$data['url'] = base_url()."transaction/giaodich";
		echo json_encode($data);
		exit();
	}
	
	//save giaodich
	function saveGiaodich(){
		$ee_id = $this->input->post('ee_id');//danh sach nhan vien tip tuong ung voi danh sach giao dich service_id
		$ghichu = $this->input->post('ghichu');//ghi chu' cho giao dich
		$service_id = $this->input->post('service_id');//danh sach dich vu tuong ung voi danh sach nhan vien tip ee_id
		$box_new = $this->input->post('box_new');//giao dich moi???
		$box_tran_id = $this->input->post('box_tran_id');//id transaction
		$cust_id = $this->input->post('cust_id');//id khach hang
		$arr_gd = $this->input->post('arr_gd');//danh sach id dich vu da giao dich
		$arr_rm = $this->input->post('arr_rm');//xoa 
		$arr_phieu = $this->input->post('arr_phieu');//danh sach phieu tuong ung voi dich vu
		$create_dt = $this->input->post('create_dt');//ngay tao
		if(empty($create_dt))$create_dt = time();
		else $create_dt = strtotime(str_replace(array("/"),array("."),$create_dt));
		$date_tmp = $this->input->post('Create_Dt');
		$arr_serv_vip = $this->input->post('arr_serv_vip');
		//lay thong tin default
		$Price = 0;
		$Money = 0;
		$Discount_Percent = 0;	
		$arr_result = array();
		//xoa dich vu da remove
		if(!empty($arr_rm))
			foreach($arr_rm as $item){
				//xoa dich vu
				$sql = "select s.Price from tientip as tt, services as s where s.Serv_ID = tt.Serv_ID and tt.ID = $item";
				$getPriceTT =  $this->CodeGenerator_model->custom_query($sql,'array');  	
				$this->CodeGenerator_model->delete(  'tientip', 'ID', $item );
				//xoa dich vu con cua dich vụ VIP
				$this->CodeGenerator_model->delete(  'transaction_vip', 'TienTip_ID', $item );
				//tinh lai thanh tien
				if(!empty($getPriceTT)) {
					$Price -= $getPriceTT[0]['Price'];
					//vi` giam ko co' nen gia = thanh tien
					$Money -= $getPriceTT[0]['Price'];
				}
			}
		
		if(!empty($date_tmp)) $ngay = str_replace(array("/"),array(""),$date_tmp);
		else $ngay= date("d",time()).date("m").date("Y",time());
		
		//xl giao dich
		if(empty($box_tran_id)){ // them giao dich moi
			$data = array(
						'Cust_ID' => $cust_id,
						//'Promo_ID' => $this->xl_str_duplacate(set_value('Promo_ID'),";"),
						'Bonus' => 0,
						'Price' => 0,
						'Discount_Percent' => 0,
						'Create_Dt' => $create_dt,
						'Money' => 0,
						'Completed' => 0
			  );
				
			 $box_tran_id = $this->CodeGenerator_model->add( 'transaction', $data, 'Tran_ID' ,true);			 
		}
		
		//lap cho tung dich vu
		if(!empty($service_id)){
		foreach($service_id as $i=>$serv_id){
			if(!empty($arr_phieu[$i])) //la phieu
			{
				$arr_child = explode(",",$arr_phieu[$i]);
				//arr_child 0: so suat
				//          1: tang
				//          2: conlai
				//          3: giam
				//          4: tientip
				//			5: phieu code
				$box_sosuat = $arr_child[0];
				$box_tang = $arr_child[1];
				$conlai = $arr_child[2];
				$giam = $arr_child[3];
				$tientip = $arr_child[4];
				$phieucode = $arr_child[5];
				
				$service   =   $this->CodeGenerator_model->get( 'services', '*', 'Serv_ID = "' . $serv_id . '"', NULL, NULL, true );  	
				//tien dich vu = thanh tien 
				$price_serv = ((($service->Price*(100-$giam)/100)*$box_sosuat)/($box_sosuat+$box_tang));
				// echo $price_serv;
				$price_serv = ($price_serv > 50 ? $price_serv - 10 : $price_serv - 5) * $service->Percent_Serv/100;
			
				
				$arr_phieu=array(
					'Cust_ID'=>$cust_id,
					'Tran_ID'=>$box_tran_id,
					'Active' => 1,
					'SoSuat' =>$box_sosuat,
					'Serv_ID' => $serv_id,
					'Gia' => 0,
					'Tang' => $box_tang,
					'GhiChu' =>$ghichu,
					'Create_Dt' =>$create_dt,
					'Saved' => 0,
					'Conlai' => $conlai,
					'PhieuCode'=>$phieucode
				);
				
				$arr_phieu['EE_ID'] = $ee_id[$i];
				$arr_phieu['TienTip'] = $tientip;
				$arr_phieu['Price_Serv'] = $price_serv * $this->PercentService($ee_id[$i]);
				//remove giao dich cu khi edit
				$this->CodeGenerator_model->delete(  'phieukh', 'ID',  $arr_gd[$i]);	
				//them giao dich hien tai khi edit
				$phieuid=$this->CodeGenerator_model->add("phieukh",$arr_phieu,'',true);
				
				//$result   =   $this->CodeGenerator_model->get( 'tientip', '*', 'ID = "' . $id . '"', NULL, NULL, true ); 
				$arr_result = $arr_phieu;
			}else //ko la phieu
			{	
				//lay thong tin gia dich vu
				$dv   =   $this->CodeGenerator_model->get( 'services', '*', 'Serv_ID = "' . $serv_id . '"', NULL, NULL, true );  
				$gia = $dv->Price;					
				$box_percent_serv = $dv->Percent_Serv;
				$price_serv = ($gia > 50 ? ($gia - 10):($gia - 5))*$box_percent_serv/100;
				//lay thong tin nhan vien
				$nv   =   $this->CodeGenerator_model->get( 'employee', '*', 'EE_ID = "' . $ee_id[$i] . '"', NULL, NULL, true );  
				$tientip =  $dv->TienTip;
				$arr_tientip = array('Serv_ID'=>$serv_id,'GhiChu' =>$ghichu);
				$arr_tientip['EE_ID'] =  $ee_id[$i];
				$arr_tientip['Price'] = $tientip;
				$arr_tientip['Price_Serv'] = $nv->Dichvu * $price_serv ;
				if($arr_gd[$i]){ //edit
					$id = $arr_gd[$i];
					$this->CodeGenerator_model->edit( 'tientip', $arr_tientip ,'ID',$id);
				}
				else //add
				{
					$arr_tientip['Tran_ID'] = $box_tran_id;
					$arr_tientip['Ngay'] = $ngay;
					$arr_tientip['Create_Dt'] = $create_dt;
					$this->CodeGenerator_model->add( 'tientip',$arr_tientip ,'ID',true );  
				}
				//get khuyen mai
				$time = $create_dt;
				$sql = "select p.* from promotion as p where (p.Serv_ID1 = '$serv_id' or p.Serv_ID2 = '$serv_id' or p.Serv_ID3 = '$serv_id') AND p.Eff_Dt < $time AND p.Exp_Dt > $time";
				$km   =   $this->CodeGenerator_model->custom_query($sql, "array");
				if(!empty($km)){
					if($km[0]['Serv_ID1'] == $serv_id) $Discount_Percent += $km[0]['Discount_Percent1'];
					if($km[0]['Serv_ID2'] == $serv_id) $Discount_Percent += $km[0]['Discount_Percent2'];
					if($km[0]['Serv_ID3'] == $serv_id) $Discount_Percent += $km[0]['Discount_Percent3'];
				}
				$Price += $gia;
				$Money += ($dv->Price * (100 - $Discount_Percent)/100);
				$arr_result = $arr_tientip;
			}
		}
		}
		//xl dich vu VIP
		//array string [xldichvu_parent],[id_transaction_vip],[service_id_vip],[sub_service_id_vip],[nhanvientip];[],[],[];...
		$arr_main = array();
		if(!empty($arr_serv_vip)){
		foreach($arr_serv_vip as $item){
			//lay thong tin gia dich vu
			$arr_vip = explode(";",$item);
			$tientip_id = 0;
			$arr1 = array(); // 1 array tientip
			$arr2 = array(); // list array transaction_vip
			$sumtientip = 0;
			$sumprice_serv = 0;
			$id_transaction_vip = 0;
			$id = 0;
			foreach($arr_vip as $item){
				$arr_child = explode(",",$item);				
				if(count($arr_child) == 5){
						if(empty($id_transaction_vip))
							$id_transaction_vip = $arr_child[2];
						if(empty($id))
							$id = $arr_child[0];
						//lay thong tin gia dich vu
						$dv   =   $this->CodeGenerator_model->get( 'services', '*', 'Serv_ID = "' . $arr_child[3] . '"', NULL, NULL, true );  
						$gia = $dv->Price;					
						$box_percent_serv = $dv->Percent_Serv;
						$price_serv = ($gia > 50 ? ($gia - 10):($gia - 5))*$box_percent_serv/100;
						//lay thong tin nhan vien
						$nv   =   $this->CodeGenerator_model->get( 'employee', '*', 'EE_ID = "' . $arr_child[4] . '"', NULL, NULL, true );  
						$tientip =  $dv->TienTip;
						//dieu kien du cua tien tip
						$arr_tran_vip = array(
							'ID'=>$arr_child[1],
							'Serv_ID'=>$arr_child[3],
							'Giam' => 0,
							'EE_ID'=> $arr_child[4],
							'Price' => $tientip,
							'Price_Serv' =>  $nv->Dichvu * $price_serv ,
							'Create_Dt' => $create_dt,
							'Serv_VIP_ID' => $id_transaction_vip
						);
						$arr2[]= $arr_tran_vip;
						$sumtientip += $arr_tran_vip['Price'];
						$sumprice_serv +=$arr_tran_vip['Price_Serv'];
				}
			}
			$dv   =   $this->CodeGenerator_model->get( 'services', '*', 'Serv_ID = "' . $id_transaction_vip . '"', NULL, NULL, true );  
			$serv_id = $id_transaction_vip;
			$arr1 = array(
				'ID' => $id,
				'Tran_ID'=> $box_tran_id,
				'Serv_ID'=> $serv_id,
				'Vip' => 1,
				'Giam' => 0,
				'EE_ID' => '',
				'Price' => $sumtientip,//tong tien tip
				'Price_Serv' => $sumprice_serv,//tong tien dich vu
				'Create_Dt' => $create_dt
			);
			$giam = 0;
			$sql = "select p.* from promotion as p where (p.Serv_ID1 = '$serv_id' or p.Serv_ID2 = '$serv_id' or p.Serv_ID3 = '$serv_id') AND p.Eff_Dt < $create_dt AND p.Exp_Dt > $create_dt";
			$km   =   $this->CodeGenerator_model->custom_query($sql, "array");
			if(!empty($km)){
				if($km[0]['Serv_ID1'] == $serv_id) $giam = $km[0]['Discount_Percent1'];
			}
			if(empty($id)){ //them moi moi cap nhat gia tien
				$Price += $dv->Price;
				$Money += ($dv->Price * (100 - $giam)/100);
				$Discount_Percent += $giam;
			}
			$arr_main[]=array(
				'arr1' => $arr1,
				'arr2' => $arr2
			);
		}
		}
		//thuc hien luu VIP
		foreach($arr_main as $vip){
			if(empty($vip['ID']))
				$tientipid=$this->CodeGenerator_model->add( 'tientip',$vip['arr1'] ,'ID',true );  
			foreach($vip['arr2'] as $child){
				if(empty($child['ID'])){
					$child['TienTip_ID'] =  $tientipid;					
					$this->CodeGenerator_model->add( 'transaction_vip',$child ,'ID');  
				}else{
					$this->CodeGenerator_model->edit( 'transaction_vip', array('EE_ID'=>$child['EE_ID']) ,'ID',$child['ID']);
				}
			}
		}
		
		
		//tinh lai thanh tien
		$result   =   $this->CodeGenerator_model->get( 'transaction', '*', 'Tran_ID = "' . $box_tran_id . '"', NULL, NULL, true );  
		$update=array(
			"Price"=>$result->Price + $Price,//tong gia
			"Money"=>$result->Money + $Money,//tong thanh tien
			"Discount_Percent"=>$result->Discount_Percent + $Discount_Percent,
			"Completed"=>0,
			"Cust_ID"=>$cust_id
		);
		$this->CodeGenerator_model->edit( 'transaction', $update ,'Tran_ID',$box_tran_id);
		$data['result'] = $arr_result;
		$data['url'] = base_url()."transaction/giaodich";
		echo json_encode($data);
		exit();
	}

	function check_transaction_customer(){
		$cust_id = $this->input->post('cust_id');//khach hang
		if(empty($cust_id)) $cust_id = 0;
		$sql ="select Tran_ID from transaction where Cust_ID = '$cust_id' and Completed != 2";
		$result = $this->CodeGenerator_model->custom_query($sql,"array");
		if(!empty($result)) echo $result[0]['Tran_ID'];
		else echo 0;
		exit();
	}
	//xl thanh toan
	function save(){
		$ee_id = $this->input->post('ee_id');//danh sach nhan vien
		$gia = $this->input->post('gia');//gia dich vu dang chon
		$giam = $this->input->post('giam');// giam gia cua dich vu dang chon
		$tientip = $this->input->post('tientip');// tien tip
		$ghichu = $this->input->post('ghichu');//not active
		$id = $this->input->post('id');//id cua tien tip hay phieu
		$phieu = $this->input->post('phieu');//bool phieu
		$service_id = $this->input->post('service_id');//id cua dich vu dang chon
		$box_new = $this->input->post('box_new');//not active
		$box_tran_id = $this->input->post('box_tran_id');//id cua transaction
		$thanhtien = $this->input->post('thanhtien');//thanh tien cua dich giao dang chon
		$cust_id = $this->input->post('cust_id');// id cua khach hang
		$create_dt = $this->input->post('create_dt');//ngay tao
		$box_percent_serv = $this->input->post('box_percent_serv');//phan tran dich vu dang chon
		$completed = $this->input->post('completed');//completed
		$box_changed = $this->input->post('box_changed');//completed
		if(empty($create_dt))$create_dt = time();
		else $create_dt = strtotime(str_replace(array("/"),array("."),$create_dt));
		$date_tmp = $this->input->post('Create_Dt');
		$vip = $this->input->post('vip');
		$vipchild = $this->input->post('vipchild');
		$vipid = $this->input->post('vipid');
		
		$currency = "vnd";
		if($currency=="vnd"){
			$tientip = $tientip/1000;
			$thanhtien = $thanhtien/1000;
			$gia = $gia/1000;
		}

		if(!empty($date_tmp)) $ngay = str_replace(array("/"),array(""),$date_tmp);
		else $ngay= date("d",time()).date("m").date("Y",time());
		
		$sodu_thanhtien = 0;
		$sodu_giam = 0;
		$sodu_price = 0;
		$arr_result = array();
		$error = 0;
		$msg = "";

		if(!empty($box_changed) && $vip==0){ //da thay doi service
			// $data['error'] = 1;
			// $data['msg'] = 1;
			// $data['box_changed'] = $box_changed;
			// echo json_encode($data);
			// exit();
			if($phieu) //la phieu
			{
				$box_sosuat = $this->input->post('box_sosuat');//so suat
				$box_tang = $this->input->post('box_tang');//tang
				$conlai = $this->input->post('conlai');//so suat con lai
				
				//tinh % dich vu
				$service   =   $this->CodeGenerator_model->get( 'services', '*', 'Serv_ID = "' . $service_id . '"', NULL, NULL, true );  	
				//tien dich vu = thanh tien 
				$price_serv = ((($service->Price*(100-$giam)/100)*$box_sosuat)/($box_sosuat+$box_tang));
				// echo $price_serv;
				$price_serv = ($price_serv > 50 ? $price_serv - 10 : $price_serv - 5) * $service->Percent_Serv/100;
				$saved = 0;
				if($completed == 2) $saved = 1;
				//tao phieu
				if($box_new){//moi
					$phieucode = "phieu".uniqid();
					
					$arr_phieu=array(
						'Cust_ID'=>$cust_id,
						'Tran_ID'=>$box_tran_id,
						'Active' => 1,
						'SoSuat' =>$box_sosuat,
						'Serv_ID' => $service_id,
						'Gia' => $thanhtien,
						'Tang' => $box_tang,
						'GhiChu' =>$ghichu,
						'Create_Dt' =>$create_dt,
						'Saved' => 0,
						'PhieuCode'=>$phieucode
					);
					$arr_phieu['Conlai'] = $conlai;
					foreach($ee_id as $bo=> $itm){
						if(!empty($itm)){
							$arr_phieu['EE_ID'] = $itm;
							$arr_phieu['TienTip'] = $tientip;
							$arr_phieu['Price_Serv'] = $price_serv * $this->PercentService($itm);
							//truong hợp tạo phiếu mới mà sd nhìu suất
							if($bo!=0){
								$arr_phieu['Gia'] = 0;
							}
							$phieuid=$this->CodeGenerator_model->add("phieukh",$arr_phieu,'',true);
						}
					}
					//$result   =   $this->CodeGenerator_model->get( 'tientip', '*', 'ID = "' . $id . '"', NULL, NULL, true ); 
					$sodu_thanhtien = $thanhtien;
					$sodu_giam = 0;
					$sodu_price = $thanhtien;
					//xoa id cua dich vu ben tientip
					$this->CodeGenerator_model->delete( 'tientip', 'ID', $id ); 
				}else{//update
					$record_phieu   =   $this->CodeGenerator_model->get( 'phieukh', '*', 'ID = "' . $id . '"', NULL, NULL, true );  					
					if(!empty($record_phieu)){
						$phieucode  = $record_phieu->PhieuCode;
						$Serv_ID = $service_id;
						$conlai = $record_phieu->Conlai;
						
						//xoa dich vu trc khi tao lai cai mới
						$sql = "select * from phieukh as p where Tran_ID = $box_tran_id and Saved = 0 and Serv_ID='$Serv_ID'";
						$arr_phieu_del = $this->CodeGenerator_model->custom_query($sql,"array");
						foreach($arr_phieu_del as $itm){
							$this->CodeGenerator_model->delete(  'phieukh', 'ID', $itm['ID'] );	
						}
						
						// if($completed == 2){
							// $this->CodeGenerator_model->edit( 'phieukh', array('Active'=>0,'Saved'=>1), 'ID',$id); 				
							// $conlai = $record_phieu->Conlai - 1;
						// }		
						
						if($conlai==0) $active = 0; else $active = 1;
						
						$arr_phieu=array(
							'Cust_ID'=>$record_phieu->Cust_ID,
							'Tran_ID'=>$box_tran_id,
							'Active' => 1,
							'SoSuat' =>$record_phieu->SoSuat,
							'Serv_ID' => $Serv_ID,
							'Gia' => $thanhtien,
							'Tang' => $record_phieu->Tang,
							'Conlai' =>$conlai,
							'GhiChu' =>$ghichu,
							'Create_Dt' => $create_dt,
							'Saved' =>0,
							'PhieuCode'=>$phieucode
						);
						
						foreach($ee_id as $itm){
							if(!empty($itm)){
								$arr_phieu['EE_ID'] = $itm;
								$arr_phieu['TienTip'] = $tientip;
								$arr_phieu['Price_Serv'] = $price_serv * $this->PercentService($itm);	
								// if($completed == 2){
								$phieuid=$this->CodeGenerator_model->add("phieukh",$arr_phieu,'',true);
								// }
								// else
									// $this->CodeGenerator_model->edit( 'phieukh', $arr_phieu, 'ID',$id);
							}									
						}
						$sodu_thanhtien = 0 ;
						$sodu_giam = 0;
						$sodu_price = 0 ;
					}
				}				
				$arr_result = $arr_phieu;
			}else //ko la phieu
			{
				//lay thong tin giao dich cua 1 dich vu da chon
				$result   =   $this->CodeGenerator_model->get( 'tientip', '*', 'ID = "' . $id . '"', NULL, NULL, true );  
				//lay thong tin gia dich vu
				$dv   =   $this->CodeGenerator_model->get( 'services', '*', 'Serv_ID = "' . $result->Serv_ID . '"', NULL, NULL, true );  
				$gia_old = $dv->Price;	
				$giam_old = $result->Giam;
				$thanhtien_old= $gia_old * (100 - $giam_old)/100;
				$thanhtien_new = $gia *(100 - $giam)/100;
				$sodu_thanhtien = $thanhtien_new - $thanhtien_old;
				$sodu_giam = $giam - $giam_old;
				$price_serv = ($gia > 50 ? ($gia - 10):($gia - 5))*$box_percent_serv/100;
				
				$arr = $ee_id;
				$arr_tientip = array('Serv_ID'=>$service_id,'GhiChu' =>$ghichu);
				
				foreach($arr as $itm){//chi co' 1 nhan vien tip ma thui
					if(!empty($itm)){
						$arr_tientip['EE_ID'] =  $itm;//nhan vien id
						$arr_tientip['Price'] = $tientip/count($arr);//tien tip
						$PercentService = $this->PercentService($itm);//% dich vu
						$arr_tientip['Price_Serv'] = $price_serv * $this->PercentService($itm);
						$arr_tientip['Giam'] = $giam;					
						if(!$box_new) //edit
							$this->CodeGenerator_model->edit( 'tientip', $arr_tientip ,'ID',$id);
						else //truong hop nay ko xay ra
						{	
						}
					}
				}
				$arr_result = $arr_tientip;
			}
		}
		
		if($box_changed==1 && $vip==1){ //da thay doi service vip
			if($vipchild == 0){ //vip parent
				//chi thay doi gia', giam, thanh tien
				$result   =   $this->CodeGenerator_model->get( 'tientip', '*', 'ID = "' . $vipid . '"', NULL, NULL, true );  
				$dv   =   $this->CodeGenerator_model->get( 'services', '*', 'Serv_ID = "' . $result->Serv_ID . '"', NULL, NULL, true ); 
				$arr_update=array(
					'giam'=>$giam
				);
				$sodu_giam += $giam - $result->Giam;
				
				$this->CodeGenerator_model->edit( 'tientip', $arr_update ,'ID',$vipid);
				$sodu_thanhtien += $thanhtien - ($dv->Price *(100 - $result->Giam)/100);
			}else{ //vip child
				//chi thay doi nhan vien tip
				foreach($ee_id as $itm){//chi co' 1 nhan vien tip ma thui
					$arr_update = array(
						"EE_ID" => $itm
					);
					$this->CodeGenerator_model->edit( 'transaction_vip', $arr_update ,'ID',$vipid);
				}
			}
		}
		
		//xl phieu ko duoc chon
		if($completed == 2){			
			$sql = "select * from phieukh as p where Tran_ID = $box_tran_id and Saved = 0";
			$arr_phieu_not_seleted = $this->CodeGenerator_model->custom_query($sql,"array");
			$arr_check = array();
			foreach($arr_phieu_not_seleted as $item){
				//cap nhat lai 			
				$item['Active'] = 1;
				$item['Saved'] = 1;
				$sql ="select count(Serv_ID) as total from phieukh where Tran_ID = $box_tran_id and Saved=0 and Serv_ID='".$item['Serv_ID']."' group by Serv_ID";
				$total = $this->CodeGenerator_model->custom_query($sql,"array");
				unset($item['ID']);
				//xl giao dich phieu mà sd nhiu suất
				$item['Conlai'] = $item['Conlai'] - $total[0]['total'];
				if($item['Conlai'] == 0){
					//cap nhat lai phieu da het han Off = 1;
					$item['Off'] = 1;
					$this->CodeGenerator_model->edit('phieukh', array('Off'=>1), 'PhieuCode',$item['PhieuCode']);
				}
				$this->CodeGenerator_model->add("phieukh",$item,'',true);
			}
			//cap nhat lại active va save
			foreach($arr_phieu_not_seleted as $item){
				//cap nhat lai 			
				$item['Active'] = 0;
				$item['Saved'] = 1;
				$this->CodeGenerator_model->edit( 'phieukh', $item, 'ID',$item['ID']);
			}
			//kiem tra ton tai phieu ma chua co dich vu
			$sql = "select t.ID from tientip as t, services as s where t.Serv_ID = s.Serv_ID and t.Tran_ID = $box_tran_id and s.SoSuat > 1";
			$bool_phieu_not_selected = $this->CodeGenerator_model->custom_query($sql,"array");
			
			if(!empty($bool_phieu_not_selected)){ // ko duoc phep hoan tat, phai chon dich vu
				$msg = "Loi luu thanh toan. Phieu moi chua co giao dich.";
				$error = 1;
				$completed = 1;
			}
		}		
		
		//tinh lai thanh tien
		$result   =   $this->CodeGenerator_model->get( 'transaction', '*', 'Tran_ID = "' . $box_tran_id . '"', NULL, NULL, true );  
		$update=array(
			"Money"=>$result->Money + $sodu_thanhtien,
			"Discount_Percent"=>$result->Discount_Percent + $sodu_giam,
			"Completed"=>$completed,
			"Price" => $result->Price + $sodu_price
		);
		$this->CodeGenerator_model->edit( 'transaction', $update ,'Tran_ID',$box_tran_id);
		$data['error'] = $error;
		$data['msg'] = $msg;
		$data['result'] = $arr_result;
		if($completed != 2)
			$data['url'] = base_url()."transaction/chitietthanhtoan/$box_tran_id";
		else
			$data['url'] = base_url()."transaction/thanhtoan";
		echo json_encode($data);
		exit();
	}
	
	function getPhieuKH(){
		$Cust_ID = $this->input->post('Cust_ID');
		$sql = "select p.*, s.Serv_Name from phieukh as p,services as s where p.Serv_ID=s.Serv_ID and p.Cust_ID ='$Cust_ID' and p.Active=1  order by Create_Dt desc";
		$phieu = $this->CodeGenerator_model->custom_query($sql,"array");
		$str = "<select name='Phieu_ID'><option value='' >Phieu moi</option>";
		foreach($phieu as $itm){
			$str.="<option value='".$itm['ID']."'>Phieu ".$itm['SoSuat']." suat - ".$itm['Serv_Name']." - con ".$itm['Conlai']." suat (".date("d/m/y H:i:s",$itm['Create_Dt']).")</option>";
		}
		$str .="</select>";
		$data['html'] = $str;
		echo json_encode($data);
		exit();
	}
	
	function xl_str_duplacate($str,$param){
		$arr = explode($param,$str);
		$arr_ =array();
		foreach($arr as $item){
			if(!in_array($item, $arr_) && !empty($item)){
				$arr_[]=$item;
			}
		}
		return implode($param,$arr_);
	}
	
	function getServInfo(){
		$serv_id = $this->input->post('serv_id');
		$serv = $this->CodeGenerator_model->get( 'services', 'Serv_ID,Cat_ID,Serv_Name,Serv_Name_EN,Price,TienTip,Percent_Serv,Time,Create_Dt', 'Serv_ID = "' . $serv_id . '"', NULL, NULL, true );  
		
		$data['html'] = "<p>Mo ta:</p>
		<p>Ten tieng viet: ".$serv->Serv_Name."</p>
		<p>Ten tieng anh: ".$serv->Serv_Name_EN."</p>";
		echo json_encode($data);
		exit();
	}
	//get danh sach service - version cu
	function getComboBoxService(){
		 $stt = $this->input->post('stt');
		 $Cust_ID = $this->input->post('Cust_ID');
		 if(empty($stt)) $stt =1;
		 $selected_cat = $this->input->post('Serv_ID'.$stt);
		$sql = "select s.*, c.Name as Category_Name from services as s, categories as c where s.Cat_ID=c.Ca_ID";
        $categories   =   $this->CodeGenerator_model->custom_query($sql, "array");
		$combobox_cats=array();
		foreach($categories as $cat){
			$combobox_cats['']="";
			$combobox_cats[$cat['Serv_ID']]=$cat['Category_Name']."-".$cat['Serv_Name'];
		}
		$style="style='width: 140px; float: left; margin-left: 5px;' id='Serv_ID".$stt."' class='services' onchange=\"service_change('Serv_ID".$stt."');\"";
		//xu ly phieu
		$sql = "select * from phieukh where Cust_ID ='$Cust_ID' and Active=1";
		$phieu = $this->CodeGenerator_model->custom_query($sql,"array");
		$dm_phieu['5'] = 'Phieu 5 suat - tang 1 xuat';
		$dm_phieu['10'] = 'Phieu 10 suat - tang 3 xuat';
		$combobox_phieu = form_dropdown('sosuat', $dm_phieu,"5");
		//phieu khach hang
		$cats_phieu=array();
		$cats_phieu[''] = "Them phieu";
		foreach($phieu as $itm){
			$cats_phieu[$itm['ID']] = "Phieu ".$itm['SoSuat']." suat - con lai ".$itm['Conlai']." suat";
		}
		
		$combobox_phieu = form_dropdown('sosuat'.$stt, $dm_phieu,"5");
		$combobox_phieu_of_kh = form_dropdown('Phieu_ID'.$stt, $cats_phieu,"");
		
		//$combobox_cats=form_dropdown('Serv_ID'.$stt, $combobox_cats,$selected_cat,$style);
		echo $this->_cbService($combobox_cats,$selected_cat,$style,$stt,"",$combobox_phieu,$combobox_phieu_of_kh);
		exit;
	}
	// Giao dich: thuc hien buoc dau tien khi khach hang den
	function giaodich(){
		$this->load_template();
		$filter = $this->input->get('filter');
		$orderby = $this->input->get('orderby');
		$time = $this->input->get('time');
		if(empty($time))
			$time=$this->input->post('transaction_dt');
		if(empty($time))
			$time = date("d/m/Y H:i:s",time());
		$this->data['time'] = $time;
		$limit = $this->getLimit("D",$time);
		//paging
        $config['base_url'] = base_url().'transaction/giaodich/';
		$config['suffix']="";
		if($filter) {
			$config['suffix'] = "/?filter=$filter&orderby=$orderby&time=$time";
			$config['first_url'] = $config['base_url']."0/?filter=$filter&orderby=$orderby&time=$time";
		}
		if(empty($config['suffix'])){
			$config['suffix'] = "/?time=$time";
			$config['first_url'] = $config['base_url']."0/?time=$time";
		}
		$sql = "select count(Tran_ID) as total from transaction where Completed >= 0 and Create_Dt >= ".$limit['datemin']." AND Create_Dt <= ".$limit['datemax'];
		$total = $this->CodeGenerator_model->custom_query($sql,"array");
		if(!empty($total)) $config['total_rows'] = $total[0]['total'];
		else $config['total_rows'] = 0;
        // $config['total_rows'] = $this->CodeGenerator_model->count('transaction');
        $config['per_page'] = PER_PAGE;	
        $this->pagination->initialize($config); 

		$start = $this->uri->segment(3);
		if(empty($start)) $start = 0;
		$perpage = $config['per_page'];
        // Get rules from config file
        // --------------------------------------------------
        //$rules                  =   $this->form_validation->_config_rules[ 'transaction_add' ];
        $rules                  =         array(array('field_id' => 'stt','label' => 'stt','control' => 'auto','class'=>'first border-right','width'=>'5%','style'=>'border-right: solid 3px #fff;'),
		array('field_id' => 'khachhang','label' => 'Khách hàng','control' => 'string','class'=>'border-right','width'=>'10%','style'=>'border-right: solid 3px #fff;'),
		array('field_id' => 'Serv_FullName','label' => 'Dịch vụ','control' => 'Array','order'=>false,'class'=>'border-right','width'=>'30%','style'=>'border-right: solid 3px #fff;'),
		//array('field_id' => 'Price','label' => 'Giá trị dịch vụ','control' => 'vnd','isedit'=>false,'rel'=>'transaction,Tran_ID,[value],Price,1','class'=>'border-right','width'=>'15%','style'=>'border-right: solid 3px #fff;'),
		array('field_id' => 'EE_Name','label' => 'Tips','control' => 'string','class'=>'border-right','width'=>'9%','style'=>'border-right: solid 3px #fff;'),
		//array('field_id' => 'Price_Serv','label' => '%<br/>Dịch Vụ','control' => 'string','class'=>'border-right','width'=>'9%','style'=>'border-right: solid 3px #fff;'),
		//array('field_id' => 'Discount_Percent','label' => 'KM','control' => 'percent','isedit'=>false,'rel'=>'transaction,Tran_ID,[value],Discount_Percent,0','class'=>'border-right','width'=>'9%','style'=>'border-right: solid 3px #fff;'),
		//array('field_id' => 'Money','label' => 'Còn lại','control' => 'vnd','isedit'=>false,'rel'=>'transaction,Tran_ID,[value],Money,1','class'=>'border-right','width'=>'9%','style'=>'border-right: solid 3px #fff;')
		);
       
		
		if(empty($filter)) $str_orderby = 'order by Tran_ID DESC'; else $str_orderby = "order by $filter $orderby";
		$sql = "select t.*, CONCAT(c.F_Name, ' ' , c.L_Name) as khachhang, p.SoSuat, p.Conlai,p.Tang from customer as c, transaction as t left join phieukh as p on t.Phieu_ID=p.ID where t.Completed >= 0 and c.Cust_ID = t.Cust_ID and t.Create_Dt >= ".$limit['datemin']." AND t.Create_Dt <= ".$limit['datemax']." $str_orderby Limit $start,$perpage";
       
		 // Make header
        // --------------------------------------------------
        $header = array( );
        foreach( $rules as $k => $item ){
            $header[ ] = $item[ 'label' ];
			$str1='';$str2='';
			if($filter == $item['field_id']){
				if($orderby == "DESC") {$orderby = "ASC";$img1="display: none;";$img2="display: inline;"; } else {$orderby = "DESC";$img1="display: inline;";$img2="display: none;";}
				$url= base_url()."transaction/giaodich/$start/?filter=$filter&orderby=$orderby&time=$time";
				$str1 = 'onmouseout="$(\'.soimg2\').toggle()" onmouseover="$(\'.soimg2\').toggle()"';
				$str2='<img class="icon ic_s_asc soimg2" alt="Ascending" title="" src="'.base_url().'resources/images/dot.gif" style="'.$img1.'"> <img class="icon ic_s_desc soimg2 hide" alt="Descending" title="" src="'.base_url().'resources/images/dot.gif" style="'.$img2.'">';
			}else $url= base_url()."transaction/giaodich/$start/?filter=".$item['field_id']."&orderby=ASC&time=$time";
			$rules[$k]['html'] ='<span><a title="" '.$str1.' href="'.$url.'">'.$item[ 'label' ].' '.$str2.'</a></span>';
			if(isset($item['order'])&&!$item['order']) $rules[$k]['html'] = $item[ 'label' ];
        }
		$this->data[ 'rules' ]  =   $rules;
		
        $this->data[ 'header' ] =   $header;
        $results=$this->CodeGenerator_model->custom_query($sql,"array");

		// print_r($results);
		// die;
        // Make action Edit/Delete
        // --------------------------------------------------
        for( $i = 0; $i < count( $results ); $i++ ){
	       $id = array_values( $results[ $i ]);
		   $Tran_ID = $results[$i]['Tran_ID'];
		   //duyet service va nguoi duoc tip
		     $str_dv = "";
			 $str_nguoitip = "";
		   $sql = "select s.Serv_Name, ca.Name, e.Personal_ID, e.Name as e_Name,tt.Price,tt.Price_Serv,tt.ID  from services as s, categories as ca, employee as e, tientip as tt where tt.Tran_ID='$Tran_ID' AND s.Cat_ID = ca.Ca_ID and e.EE_ID = tt.EE_ID and tt.Serv_ID = s.Serv_ID";
		   // echo $sql;die;
		   $services = $this->CodeGenerator_model->custom_query($sql,"array");
		   $tiendv = "";
		   foreach($services as $t){
				$duynhat1 =  uniqid();
				$duynhat2 =  uniqid();
				$str_dv .=$t['Serv_Name']."(".$t['Name'].")"."<br/>";
				 $str_nguoitip .= '<span class="doubleclick" id="pibien'.$duynhat1.'" rel="'.$duynhat1.'">'.$t['e_Name'].'</span>'.'<input rel="auto" class="edit" style="display:none;" value="'.$t['e_Name'].'" type="text" id="auto'.$duynhat1.'" />'.'<input id="'.$duynhat1.'" type="hidden" rel="tientip,ID,'.$t['ID'].',EE_ID" value="'.$t['Personal_ID'].'" />'.$this->_getStringAutoEE($duynhat1).'<span class="doubleclick" id="pibien'.$duynhat2.'" rel="'.$duynhat2.'">'.'('.$t['Price'].'k)</span>'.'<input class="edit" style="display:none;" value="'.$t['Price'].'" type="text" rel="tientip,ID,'.$t['ID'].',Price,0,0,([value]k)" id="'.$duynhat2.'" /><br/>';
				$tiendv .= $t['e_Name']."(".$t['Price_Serv']."k)<br/>";
		   } 
			//vip
			$sql = "select s.Serv_Name, ca.Name,tt.Price,tt.Price_Serv,tt.ID from services as s, categories as ca, employee as e, tientip as tt where tt.Tran_ID='$Tran_ID' AND s.Cat_ID = ca.Ca_ID and tt.Serv_ID = s.Serv_ID and tt.Vip=1 Group by tt.ID";
		   $services = $this->CodeGenerator_model->custom_query($sql,"array");
		   foreach($services as $t){
				$str_dv .=$t['Serv_Name']."(".$t['Name'].")"."<br/>";
				$sql = "select e.Personal_ID, e.Name as e_Name,tv.Price from transaction_vip as tv, employee as e where e.EE_ID=tv.EE_ID and tv.TienTip_ID='".$t['ID']."'";
				$child=$this->CodeGenerator_model->custom_query($sql,"array");
				foreach($child as $k){
					$str_nguoitip .= $k['e_Name']."(".$k['Price']."k), ";
				}
		   }
		   //end vip
		   //phieu
		   $sql = "select s.Serv_Name, ca.Name, e.Personal_ID, e.Name as e_Name, p.TienTip,p.SoSuat, p.Conlai,p.Price_Serv from services as s, categories as ca, employee as e, phieukh as p where p.Tran_ID='$Tran_ID' and p.EE_ID = e.EE_ID and s.Cat_ID = ca.Ca_ID and p.Serv_ID = s.Serv_ID and p.Active = 1";
		   $phieus = $this->CodeGenerator_model->custom_query($sql,"array");
		   foreach($phieus as $t){
				$str_dv .="Phieu ".$t['SoSuat']." suat - con lai ".$t['Conlai']." suat - ".$t['Serv_Name']."(".$t['Name'].")"."<br/>";
				$str_nguoitip .= $t['Personal_ID']."(".$t['TienTip']."k), ";
				$tiendv .=$t['e_Name']."(".$t['Price_Serv']."k)";
		   }
		   //end phieu
		   $results[$i]['stt'] =$i+1;
		   $results[$i]['Serv_FullName'] = substr($str_dv, 0, -3);
		   $results[$i]['EE_Name'] = "<span style='float:left;width:70px;'>".substr($str_nguoitip,0,-2)."</span>";
		   $results[$i]['Price_Serv'] = $tiendv;
		   if(!$results[$i]['Completed']){
            $results[ $i ][ 'Edit'   ]   =  anchor( base_url( ) . 'transaction/chitietgiaodich/' . $id[ 0 ], 'Edit');  
            $results[ $i ][ 'Delete' ]   =  anchor( 
                        base_url( ) . 'index.php/transaction/delete/' . $id[ 0 ], 
                        'Del',
                        array( 'onClick' => 'return deletechecked(\' ' . base_url() . 'transaction/delete/' . $id[ 0 ] . ' \')' ) );  
			}else{				
				$results[ $i ][ 'Edit'   ] = "";
				$results[ $i ][ 'Delete'   ] = "";
				if($results[$i]['Completed'] == 1) $results[ $i ][ 'Edit'   ] = "Dang thanh toan";
				if($results[$i]['Completed'] == 2) $results[ $i ][ 'Edit'   ] = "Hoan tat";
			}
        }	
        $this->data[ 'results'        ]     =   $results;
        $this->data[ 'master_limited' ]     =   explode(',', 'stt,Tran_ID,Cust_ID,SoSuat,Conlai,Serv_FullName,EE_Name,Bonus,khachhang,Serv_ID,Promo_ID,Price,Discount_Percent,Create_Dt,Money,Completed,Price_Serv');
		
		//lay tien tips cho moi nhan vien
		
		$sql = "select EE_ID, Personal_ID,Name  from employee where role = 1 and active = 1 and Personal_ID!='test' and Name!='test'";
		$results = $this->CodeGenerator_model->custom_query($sql,"array");
		$sum_dv = 0;
		foreach($results as $k=> $item){
			$ee_id = $item['EE_ID'];	
			$price_serv = 0;
			$sql = "select sum(tt.Price) as total from tientip as tt where tt.EE_ID='$ee_id' and tt.Create_Dt >= ".$limit['datemin']." AND tt.Create_Dt <= ".$limit['datemax']."";
			$result = $this->CodeGenerator_model->custom_query($sql,"array");
			if(!empty($result)) $price_serv +=$result[0]['total'];
			$sql = "select sum(p.TienTip) as total from phieukh as p where p.EE_ID='$ee_id' and p.Create_Dt >= ".$limit['datemin']." AND p.Create_Dt <= ".$limit['datemax']."";
			$result = $this->CodeGenerator_model->custom_query($sql,"array");
			if(!empty($result)) $price_serv +=$result[0]['total'];
			$sum_dv +=$price_serv;
			$results[$k]['Price'] = $price_serv;
		}
		$this->data['tientips'] = $results;
		
	   //die;
       $this->data[ 'action']     =   array(array('id' => 'new','label' => 'Giao dich moi','url' => 'transaction/chitietgiaodich',),array('id' => 'delete','label' => 'Delete','url' => '',),);
        // $this->load->view( 'transaction_list', $this->data ); 
		$this->template->write( 'title', 'Spa - Giao dich' );
        $this->template->write_view( 'content', 'giaodich.php',$this->data );
        $this->template->render();
	}
	
	//chi tiet giao dich : chi tiet cua giao dich
	function chitietgiaodich(){
		$this->load_template();
        $this->data[ 'custom_error' ] = '';
		$username = "noname";
		$userid = 0;
		$Cust_ID =  $this->input->get('Cust_ID');
		$goto=false;
		if(empty($Cust_ID))
			$Cust_ID = $this->input->post('Cust_ID');
		else $goto = true;
        
        if( $this->form_validation->run( 'transaction_edit' ) == false ){
            $this->data[ 'custom_error' ] = ( validation_errors( ) ? '<div class="form_error">' . validation_errors( ) . '</div>' : false );

        }else{                            
            $data = array(
                'Personal_ID' => $this->input->post('Personal_ID'),
					'Promo_ID' => $this->input->post('Promo_ID'),
					'Create_Dt' => $this->input->post('Create_Dt'),
					'Money' => $this->input->post('Money'),
					'Completed' => $this->input->post('Completed')
            );
			if( $this->CodeGenerator_model->edit( 'transaction', $data, 'Tran_ID', $this->input->post( 'Tran_ID' ) ) == TRUE ){
				redirect( base_url( ) . 'index.php/transaction/manage/' );
			}else{
				$this->data[ 'custom_error' ] = '<div class="form_error"><p>An Error Occured</p></div>';
			}
		}
		if(empty($Cust_ID)){
			$result   =   $this->CodeGenerator_model->get( 'transaction', '*', 'Tran_ID = "' . $this->uri->segment( 3 ) . '"', NULL, NULL, true );  
		}
		else {//lay giao dich gan nhat
			$result   =   $this->CodeGenerator_model->get( 'transaction', '*', 'Cust_ID = "' . $Cust_ID . '"', NULL, NULL, true,'','Create_Dt DESC' ); 		
		}
		//get services cua 1 transaction
		if(!empty($result)){
			$Tran_ID = $result->Tran_ID;
			$Cust_ID = $result->Cust_ID;
		}
		else $Tran_ID=0;
		
			// + dich vu
		$sql = "select tt.ID,s.Serv_Name, ca.Name, e.Personal_ID, e.Name as e_Name,tt.Price as TienTip,tt.Price_Serv,tt.ID,s.Price as Gia, tt.Giam,tt.GhiChu, tt.Serv_ID, e.EE_ID from services as s, categories as ca, employee as e, tientip as tt where tt.Tran_ID='$Tran_ID' AND s.Cat_ID = ca.Ca_ID and e.EE_ID = tt.EE_ID and tt.Serv_ID = s.Serv_ID";
		  //echo $sql;//die;
		 $services = $this->CodeGenerator_model->custom_query($sql,"array");
		 foreach($services as $k => $item){
			$services[$k]['SoSuat'] = "";			
			$services[$k]['Conlai'] = "";		
			$services[$k]['Tang'] = "";		
			$services[$k]['Serv_Full'] = $item['Serv_Name']."(".$item['Name'].")";	
			if($goto) $services[$k]['ID'] = "";		
		 }
		 
		 // + phieu
		 //lay giao dich có sử dụng phiếu con hieu luc
		$sql = "Select p.Tran_ID, p.Serv_ID from phieukh as p where p.Cust_ID ='$Cust_ID' and p.Conlai > 0 and p.Off = 0 GROUP BY p.Tran_ID order by Create_Dt desc";
			
		$phieutontai = $this->CodeGenerator_model->custom_query($sql,"array");
		$str_in = "(";
		$arr_in = array();
		foreach($phieutontai as $itm){
			if(!in_array($itm['Serv_ID'],$arr_in)){
				$arr_in[] = $itm['Serv_ID'];
				$str_in .="'".$itm['Tran_ID']."',";
			}
		}
		$str_in .="'".$Tran_ID."')";
		//$str_in = substr($str_in,0,-1);
		//$str_in .=")";
		$sql = "select p.ID, s.Serv_Name, ca.Name, e.Personal_ID, e.Name as e_Name, p.TienTip,p.SoSuat, p.Conlai,p.Price_Serv,p.Gia, p.Giam,p.GhiChu, p.Serv_ID, e.EE_ID, p.Tang,p.PhieuCode from services as s, categories as ca, employee as e, phieukh as p where p.Tran_ID IN $str_in and p.EE_ID = e.EE_ID and s.Cat_ID = ca.Ca_ID and p.Serv_ID = s.Serv_ID and p.Active = 1 and p.Conlai>0 and p.Off=0 order by p.ID desc";
		
		$phieus = $this->CodeGenerator_model->custom_query($sql,"array");
		$arr_check = array();
		$phieus_new = array();
		foreach($phieus as $k=>$t){
			if(!in_array($t['PhieuCode'],$arr_check)){
				$phieus[$k]["Serv_Full"] = "Phieu ".$t['SoSuat']." suat - con lai ".$t['Conlai']." suat - ".$t['Serv_Name']."(".$t['Name'].")";
				if($goto) $phieus[$k]['ID'] = "";		
				$arr_check[] = $t['PhieuCode'];
				$phieus_new[] = $phieus[$k];
			}
		 }
		 $phieus = $phieus_new;
		 $services = array_merge($services, $phieus);
		 
		 //dich vu vip
		 $sql = "select tt.Serv_ID,tt.ID,s.Serv_Name, ca.Name from tientip as tt, services as s,categories as ca where s.Serv_ID = tt.Serv_ID and tt.Tran_ID='$Tran_ID' and tt.Vip=1 AND s.Cat_ID = ca.Ca_ID and tt.Vip = 1";
		 // $sql = "select tt.Serv_ID,tt.ID from tientip as tt where tt.Tran_ID='$Tran_ID' and tt.Vip=1";
		 $services_vip = $this->CodeGenerator_model->custom_query($sql,"array");
		  foreach($services_vip as $i=> $t){
				$sql = "select e.Personal_ID, e.Name as e_Name,tv.Price,tv.ID,s.Serv_Name, ca.Name,tv.Serv_ID,e.EE_ID from transaction_vip as tv, employee as e,categories as ca, services as s where e.EE_ID=tv.EE_ID and tv.TienTip_ID='".$t['ID']."' AND s.Cat_ID = ca.Ca_ID and tv.Serv_ID = s.Serv_ID";
				$child=$this->CodeGenerator_model->custom_query($sql,"array");
				$services_vip[$i]['child'] = $child;
		  }
		  //end dich vu vip
		 
		 //lay danh muc
		$sql = "select c.* from categories as c order by c.Name";
		$categories   =   $this->CodeGenerator_model->custom_query($sql, "array");
		 //get info customer
		 $customer = null;
		 if(!empty($Cust_ID))
			$customer =  $this->CodeGenerator_model->get( 'customer', '*', 'Cust_ID = "' . $Cust_ID . '"', NULL, NULL, true );  
		
		//get list nhanvien
		 $sql = "select * from employee where role!=".ADMINISTRATOR." AND Personal_ID !='test'";
		 $employers= $this->CodeGenerator_model->custom_query($sql,"array");
		 
		 //lay comments
		 if(!empty($Tran_ID)){
		  $sql = "select * from comments where Tran_ID = $Tran_ID order by Create_Dt desc";
		 $comments= $this->CodeGenerator_model->custom_query($sql,"array");
		 }else{$comments=array();}
		 // print_r($services);
		$this->data['categories'] = $categories;
		$this->data['employers'] = $employers;
		$this->data['result'] = $result;
		$this->data['services'] = $services;
		$this->data['services_vip'] = $services_vip;
		$this->data['customer'] = $customer;
		$this->data['comments'] = $comments;
		$this->data['isedit'] = $Tran_ID;
		$this->data['goto'] = $goto;
		if($goto && !empty($result)) $result->Tran_ID=0;
		// $this->load->view( 'transaction_edit', $this->data );		
		$this->template->write( 'title', 'Chi tiet giao dich' );
        $this->template->write_view( 'content', 'chitietgiaodich.php',$this->data );
        $this->template->render();
	}
	
	function getListServiceFollowDM(){
		$id = $this->input->get("id");
		if(empty($id)) $id=0;
		 //lay danh muc
		$sql = "select s.vip,s.Serv_ID,s.Serv_Name, c.Name from services as s, categories as c where Cat_ID=$id and s.Cat_ID = c.Ca_ID  order by Serv_Name";
		$services   =   $this->CodeGenerator_model->custom_query($sql, "array");
		$html = "";
		foreach($services as $item){
			$html.='<div class="item" style="border: 1px solid transparent;"><span title="'.$item['Serv_Name'].'">'.cat_chuoi($item['Serv_Name'],20).'</span><input type="hidden" value="'.$item['Serv_ID'].'" name="service"><input type="hidden" value="'.$item['vip'].'" name="vip"><input type="hidden" value="'.$item['Name'].'" name="category_name"></div>';
		}
		echo $html;
		exit();
	}
	
	function getListServiceVIP(){
		$id = $this->input->post("serv_id");
		if(empty($id)) $id=0;
		$sql = "select s.Serv_Name, c.Name from services as s, categories as c  where s.Serv_ID ='$id' and s.Cat_ID = c.Ca_ID";
		$service_vip   =   $this->CodeGenerator_model->custom_query($sql, "array"); 
		 //lay danh muc
		 if(!empty($service_vip)){
			$sql = "select sv.*,s.Serv_Name, c.Name from services_vip as sv, services as s, categories as c  where s.Cat_ID = c.Ca_ID and s.Serv_ID = sv.sub_services_id and services_id='$id' order by s.Serv_Name";
			$services   =   $this->CodeGenerator_model->custom_query($sql, "array");
			$html = '<div class="parent_group"><span style="width: 300px;font-weight:bold;color:#cfa62b;">'.$service_vip[0]['Serv_Name'] .'-'.$service_vip[0]['Name'].'</span><a title="Remove " href="javascript:" style="position: relative; top: -3px; right: 1px;" class="remove">x</a>';
			foreach($services as $k => $item){
				$full_name = $item['Serv_Name'].' - '.$item['Name'];
				$html.='<div class="parent" style="border: 1px solid transparent;"><div class="item service shadow"><span title="'.$full_name.'">'.cat_chuoi($full_name,25).'</span></div> <hr><div class="item nhanvien shadow nhapnhay'.$k.'" rel="#chitiet3 .nhapnhay'.$k.'"><span>them nv</span></div><hr><div class="item descr shadow"><span>Mô tả</span></div><input type="hidden" value="'.$item['sub_services_id'].'" name="service"><input type="hidden" value="" name="nhanvien"><input type="hidden" value="0" name="xldichvu"><input type="hidden" value="" name="phieu"></div>';
			}
			echo $html.'<input type="hidden" value="'.$id.'" name="service_vip_id"><input type="hidden" value="0" name="xldichvu_parent"></div>';
		}else{echo "";}
		exit();
	}
    
    function getListServiceNormal(){
       $id = $this->input->get("id");
		if(empty($id)) $id=0;
		 //lay danh muc
		$sql = "select * from services where Cat_ID=$id and vip=0 order by Serv_Name";
		$services   =   $this->CodeGenerator_model->custom_query($sql, "array");
		$html = "";
		foreach($services as $item){
			$html.='<div class="item" style="border: 1px solid transparent;"><span title="'.$item['Serv_Name'].'">'.cat_chuoi($item['Serv_Name'],20).'</span><input type="hidden" value="'.$item['Serv_ID'].'" name="service"></div>';
		}
		echo $html;
		exit(); 
    }
	
	function thanhtoan(){
		$this->load_template();
		$filter = $this->input->get('filter');
		$orderby = $this->input->get('orderby');
		$time = $this->input->get('time');
		if(empty($time))
			$time=$this->input->post('transaction_dt');
		if(empty($time))
			$time = date("d/m/Y H:i:s",time());
		$this->data['time'] = $time;
		
		$limit = $this->getLimit("D",$time);

		//paging
        $config['base_url'] = base_url().'transaction/manage/';
		$config['suffix']="";
		if($filter) {
			$config['suffix'] = "/?filter=$filter&orderby=$orderby&time=$time";
			$config['first_url'] = $config['base_url']."0/?filter=$filter&orderby=$orderby&time=$time";
		}
		if(empty($config['suffix'])){
			$config['suffix'] = "/?time=$time";
			$config['first_url'] = $config['base_url']."0/?time=$time";
		}
		$sql = "select count(Tran_ID) as total from transaction where Completed >= 0 and Create_Dt >= ".$limit['datemin']." AND Create_Dt <= ".$limit['datemax'];
		$total = $this->CodeGenerator_model->custom_query($sql,"array");
		if(!empty($total)) $config['total_rows'] = $total[0]['total'];
		else $config['total_rows'] = 0;
        // $config['total_rows'] = $this->CodeGenerator_model->count('transaction');
        $config['per_page'] = PER_PAGE;	
        $this->pagination->initialize($config); 

		$start = $this->uri->segment(3);
		if(empty($start)) $start = 0;
		$perpage = $config['per_page'];
        // Get rules from config file
        // --------------------------------------------------
        //$rules                  =   $this->form_validation->_config_rules[ 'transaction_add' ];
        $rules                  =         array(array('field_id' => 'stt','label' => 'stt','control' => 'auto','class'=>'first border-right','width'=>'5%','style'=>'border-right: solid 3px #fff;'),
		array('field_id' => 'khachhang','label' => 'Khách hàng','control' => 'string','class'=>'border-right','width'=>'10%','style'=>'border-right: solid 3px #fff;'),
		array('field_id' => 'Serv_FullName','label' => 'Dịch vụ','control' => 'Array','order'=>false,'class'=>'border-right','width'=>'30%','style'=>'border-right: solid 3px #fff;'),
		array('field_id' => 'Price','label' => 'Giá','control' => 'vnd','isedit'=>false,'rel'=>'transaction,Tran_ID,[value],Price,1','class'=>'border-right','width'=>'15%','style'=>'border-right: solid 3px #fff;'),
		array('field_id' => 'EE_Name','label' => 'Tips','control' => 'string','class'=>'border-right','width'=>'9%','style'=>'border-right: solid 3px #fff;'),
		array('field_id' => 'Price_Serv','label' => '%<br/>Dịch Vụ','control' => 'string','class'=>'border-right','width'=>'9%','style'=>'border-right: solid 3px #fff;'),
		array('field_id' => 'Discount_Percent','label' => 'Giam','control' => 'Array','isedit'=>false,'rel'=>'transaction,Tran_ID,[value],Discount_Percent,0','class'=>'border-right c','width'=>'9%','style'=>'border-right: solid 3px #fff;'),
		array('field_id' => 'Money','label' => 'Thanh tien','control' => 'vnd','isedit'=>false,'rel'=>'transaction,Tran_ID,[value],Money,1','class'=>'border-right','width'=>'9%','style'=>'border-right: solid 3px #fff;'));
       
		
		if(empty($filter)) $str_orderby = 'order by Tran_ID DESC'; else $str_orderby = "order by $filter $orderby";
		$sql = "select t.*, CONCAT(c.F_Name, ' ' , c.L_Name) as khachhang, p.SoSuat, p.Conlai,p.Tang from customer as c, transaction as t left join phieukh as p on t.Phieu_ID=p.ID where t.Completed >= 0 and c.Cust_ID = t.Cust_ID and t.Create_Dt >= ".$limit['datemin']." AND t.Create_Dt <= ".$limit['datemax']." $str_orderby Limit $start,$perpage";
       
		 // Make header
        // --------------------------------------------------
        $header = array( );
        foreach( $rules as $k => $item ){
            $header[ ] = $item[ 'label' ];
			$str1='';$str2='';
			if($filter == $item['field_id']){
				if($orderby == "DESC") {$orderby = "ASC";$img1="display: none;";$img2="display: inline;"; } else {$orderby = "DESC";$img1="display: inline;";$img2="display: none;";}
				$url= base_url()."transaction/manage/$start/?filter=$filter&orderby=$orderby&time=$time";
				$str1 = 'onmouseout="$(\'.soimg2\').toggle()" onmouseover="$(\'.soimg2\').toggle()"';
				$str2='<img class="icon ic_s_asc soimg2" alt="Ascending" title="" src="'.base_url().'resources/images/dot.gif" style="'.$img1.'"> <img class="icon ic_s_desc soimg2 hide" alt="Descending" title="" src="'.base_url().'resources/images/dot.gif" style="'.$img2.'">';
			}else $url= base_url()."transaction/manage/$start/?filter=".$item['field_id']."&orderby=ASC&time=$time";
			$rules[$k]['html'] ='<span><a title="" '.$str1.' href="'.$url.'">'.$item[ 'label' ].' '.$str2.'</a></span>';
			if(isset($item['order'])&&!$item['order']) $rules[$k]['html'] = $item[ 'label' ];
        }
		$this->data[ 'rules' ]  =   $rules;
		
        $this->data[ 'header' ] =   $header;
	   //lay danh sach thanh toan trong ngay
        $results=$this->CodeGenerator_model->custom_query($sql,"array");
        for( $i = 0; $i < count( $results ); $i++ ){
	       $id = array_values( $results[ $i ]);
		   $Tran_ID = $results[$i]['Tran_ID'];
		   //duyet service va nguoi duoc tip
		     $str_dv = "";
			 $str_nguoitip = "";
		   $sql = "select s.Serv_Name, ca.Name, e.Personal_ID, e.Name as e_Name,tt.Price,tt.Price_Serv,tt.ID  from services as s, categories as ca, employee as e, tientip as tt where tt.Tran_ID='$Tran_ID' AND s.Cat_ID = ca.Ca_ID and e.EE_ID = tt.EE_ID and tt.Serv_ID = s.Serv_ID";
		   // echo $sql;die;
		   $services = $this->CodeGenerator_model->custom_query($sql,"array");
		   $tiendv = "";
		   foreach($services as $t){
				$duynhat1 =  uniqid();
				$duynhat2 =  uniqid();
				$str_dv .=$t['Serv_Name']."(".$t['Name'].")"."<br/><center>------</center>";
				 $str_nguoitip .= '<span class="doubleclick" id="pibien'.$duynhat1.'" rel="'.$duynhat1.'">'.$t['e_Name'].'</span>'.'<input rel="auto" class="edit" style="display:none;" value="'.$t['e_Name'].'" type="text" id="auto'.$duynhat1.'" />'.'<input id="'.$duynhat1.'" type="hidden" rel="tientip,ID,'.$t['ID'].',EE_ID" value="'.$t['Personal_ID'].'" />'.$this->_getStringAutoEE($duynhat1).'<span class="doubleclick" id="pibien'.$duynhat2.'" rel="'.$duynhat2.'">'.'('.$t['Price'].'k)</span>'.'<input class="edit" style="display:none;" value="'.$t['Price'].'" type="text" rel="tientip,ID,'.$t['ID'].',Price,0,0,([value]k)" id="'.$duynhat2.'" /><br/>';
				$tiendv .= $t['e_Name']."(".$t['Price_Serv']."k)<br/>";
		   } 

			//vip
			$sql = "select s.Serv_Name, ca.Name,tt.Price,tt.Price_Serv,tt.ID from services as s, categories as ca, employee as e, tientip as tt where tt.Tran_ID='$Tran_ID' AND s.Cat_ID = ca.Ca_ID and tt.Serv_ID = s.Serv_ID and tt.Vip=1 Group by tt.ID";
		   $services = $this->CodeGenerator_model->custom_query($sql,"array");
		   foreach($services as $t){
				$str_dv .=$t['Serv_Name']."(".$t['Name'].")"."<br/><center>------</center>";
				$sql = "select e.Personal_ID, e.Name as e_Name,tv.Price,tv.Price_Serv from transaction_vip as tv, employee as e where e.EE_ID=tv.EE_ID and tv.TienTip_ID='".$t['ID']."'";
				$child=$this->CodeGenerator_model->custom_query($sql,"array");
				foreach($child as $k){
					$str_nguoitip .= $k['e_Name']."(".$k['Price']."k), ";
					$tiendv .=$k['e_Name']."(".$k['Price_Serv']."k)";
				}
				
		   }
		   //end vip
		   //phieu
		   $sql = "select s.Serv_Name, ca.Name, e.Personal_ID, e.Name as e_Name, p.TienTip,p.SoSuat, p.Conlai,p.Price_Serv from services as s, categories as ca, employee as e, phieukh as p where p.Tran_ID='$Tran_ID' and p.EE_ID = e.EE_ID and s.Cat_ID = ca.Ca_ID and p.Serv_ID = s.Serv_ID and p.Active = 1";
		   $phieus = $this->CodeGenerator_model->custom_query($sql,"array");
		   foreach($phieus as $t){
				$str_dv .="Phieu ".$t['SoSuat']." suat - con lai ".$t['Conlai']." suat - ".$t['Serv_Name']."(".$t['Name'].")"."<br/><center>------</center>";
				$str_nguoitip .= $t['Personal_ID']."(".$t['TienTip']."k), ";
				$tiendv .=$t['e_Name']."(".$t['Price_Serv']."k)";
		   }
		   //end phieu
		   $results[$i]['stt'] =$i+1;
		   $results[$i]['Serv_FullName'] = substr($str_dv, 0, -28);
		   $results[$i]['EE_Name'] = "<span style='float:left;'>".substr($str_nguoitip,0,-2)."</span>";
		   $results[$i]['Price_Serv'] = $tiendv;
		  
		   if($results[$i]['Completed']!=2){
            $results[ $i ][ 'Edit'   ]   =  anchor( base_url( ) . 'transaction/chitietthanhtoan/' . $id[ 0 ], 'Edit');  
            $results[ $i ][ 'Delete' ]   =  anchor( 
                        base_url( ) . 'index.php/transaction/delete/' . $id[ 0 ], 
                        'Del',
                        array( 'onClick' => 'return deletechecked(\' ' . base_url() . 'transaction/delete/' . $id[ 0 ] . ' \')' ) );  
			}else{
				$results[ $i ][ 'Edit'   ] = anchor( base_url( ) . 'transaction/chitietthanhtoan/' . $id[ 0 ], 'Xem');  
				$results[ $i ][ 'Delete'   ] = "";
			}
        }		
        $this->data[ 'results'        ]     =   $results;
        $this->data[ 'master_limited' ]     =   explode(',', 'stt,Tran_ID,Cust_ID,EE_Name,SoSuat,Serv_FullName,Price_Serv,Bonus,khachhang,Serv_ID,Promo_ID,Price,Discount_Percent,Create_Dt,Completed,Money');
		
		//lay tien tips cho moi nhan vien
		
		$results_tientip = $this->getResultsTienTip($limit['datemin'],$limit['datemax']);
		
		$this->data['tientips'] = $results_tientip['results'];
		$this->data['sum_tientip'] = $results_tientip['sum_tt'];
		
	   //die;
       $this->data[ 'action'         ]     =   array();
        // $this->load->view( 'transaction_list', $this->data ); 
		$this->template->write( 'title', 'Spa - Thanh toan' );
        $this->template->write_view( 'content', 'thanhtoan.php',$this->data );
        $this->template->render();
	}
	
	function _cbService($combobox_cats,$selected_cat,$style,$i,$s,$combobox_phieu,$combobox_phieu_of_kh){
		
		return '<span style=" clear:both; float:left; padding:5px;border:medium dotted;"><span style=" clear:both; float:left; padding:5px;">
                <p><label style="float: left; text-align: right; margin-right: 5px; width: 135px;" for="EE_ID">Phiếu:</label>          
				 <input type="checkbox" name="muaphieu'.$i.'" id="muaphieu'.$i.'" value="1" />
                </p></span>
				<span class="phieu'.$i.'" style="display:none; clear:both; float:left; padding:5px;">
                <p><label style="float: left; text-align: right; margin-right: 5px; width: 135px;" for="EE_ID">Chon</label>          
				'.$combobox_phieu_of_kh.'
                </p></span>
				<span class="phieu'.$i.' themphieu'.$i.'" style="display:none; clear:both; float:left; padding:5px;">
				<p><label style="float: left; text-align: right; margin-right: 5px; width: 135px;" for="EE_ID">Loại phiếu</label>          
				'.$combobox_phieu.'
                </p>
				<p><label style="float: left; text-align: right; margin-right: 5px; width: 135px;" for="ConLai">Con` lai</label>          
				<input style="float:left;" type="text" name="conlai'.$i.'" value="5" id="conlai'.$i.'" />
                </p>
				</span><p style="clear:both;"><div class="dphieu'.$i.'">
					<label style="float: left; text-align: right; margin-right: 5px; width: 135px;" for="Price">Dịch vụ '.$i.$s.'</label>'.form_dropdown('Serv_ID'.$i, $combobox_cats,$selected_cat,$style).'</p><span style=" clear:both; float:left; padding:5px;"><label style="float: left; text-align: right; margin-right: 5px; width: 135px;" for="Price">Giá</label><input type="text" name="gia'.$i.'" value="0" id="gia'.$i.'" /></span></p><span style=" clear:both; float:left; padding:5px;"><label style="float: left; text-align: right; margin-right: 5px; width: 135px;" for="Price">Giảm</label><input type="text" value="0" name="giam'.$i.'" id="giam'.$i.'" /></span><span style=" clear:both; float:left; padding:5px;"><label style="float: left; text-align: right; margin-right: 5px; width: 135px;" for="Price">Thành tiền</label><input type="text" value="0" name="thanhtien'.$i.'" id="thanhtien'.$i.'" /></span></div><span style=" clear:both; float:left; padding:5px;"><label style="float: left; text-align: right; margin-right: 5px; width: 135px;" for="Price">Tien tip</label><input type="text" value="" name="tientip'.$i.'" id="tientip'.$i.'" /></span><span style=" clear:both; float:left; padding:5px;"><label style="float: left; text-align: right; margin-right: 5px; width: 135px;" for="Price">Nguoi tip</label><input type="text" value="" name="EE_Name'.$i.'"  id="EE_Name'.$i.'" /><input type="hidden" value="" name="EE_ID'.$i.'" id="EE_ID'.$i.'" /><input type="hidden" value="0" name="Percent_Serv'.$i.'" id="Percent_Serv'.$i.'" /></label></span>	
<span style=" clear:both; float:left; padding:5px;"><label style="float: left; text-align: right; margin-right: 5px; width: 135px;" for="Price">Ghi chu</label><input type="text" value="" name="ghichu'.$i.'" id="ghichu'.$i.'" /></span>
			</span><script>$( "#EE_Name'.$i.'" )
			.bind( "keydown", function( event ) {
			if ( event.keyCode === $.ui.keyCode.TAB &&
				$( this ).data( "ui-autocomplete" ).menu.active ) {
			  event.preventDefault();
			}
		  })
			.autocomplete({
		source: "'.base_url().'transaction/searchnv",
		focus: function() {
          // prevent value inserted on focus
          return false;
        },
		minLength: 1,
		select: function( event, ui ) {
		  //$("#EE_Name'.$i.'").val(ui.item.value);
		  //$("#EE_ID'.$i.'").val(ui.item.id);
          //return false;		
		  var terms = split($("#EE_ID'.$i.'").val());
		var display = split($("#EE_Name'.$i.'").val());
		//alert(display);
          // remove the current input
          terms.pop();
		  display.pop();
          // add the selected item
          terms.push( ui.item.id );
		  display.push(ui.item.value);
          // add placeholder to get the comma-and-space at the end
          terms.push( "" );
          $("#EE_ID'.$i.'").val(terms.join( "," ));
		  display.push("");
		  $("#EE_Name'.$i.'").val(display.join(", "));
          return false;
			// $("#Cust_ID").val(ui.item.id);
		}
	});
	$("#muaphieu'.$i.'").click(function(){
		var ischeck = $(this).is(":checked");
		if(ischeck) {
			$(".phieu'.$i.'").show("slow");
			//$("#themdichvu").hide("slow");		
			$("select[name=\'Phieu_ID\']").change();
		}
		else {
			$(".phieu'.$i.'").hide("slow");
			//$("#themdichvu").show("slow");		
			$("#Serv_ID'.$i.'").attr("disabled",false);
		}
	});
	$("select[name=\'Phieu_ID'.$i.'\']").change(function(){
		var phieuid = $("select[name=\'Phieu_ID'.$i.'\'] option:selected").val();
		if(phieuid){//ton tai phieu
			$(".themphieu'.$i.'").hide("slow");
			$(".dphieu'.$i.'").hide("slow");
			$("#Serv_ID'.$i.'").attr("disabled",true);
			$.ajax({
				type: "post",
				url: "'.base_url().'transaction/getTienTipByID",
				data: {ID: phieuid
					},
				success: function(data){
						 var R = eval(\'(\' + data + \')\'); 
						 $("#tientip'.$i.'").val(R.TienTip);
				},
				statusCode:{
					404: function(){
						
					}
				}
			});
		}else{
			$(".themphieu'.$i.'").show("slow");
			$(".dphieu'.$i.'").show("slow");
			$("#Serv_ID'.$i.'").attr("disabled",false);
		}
	});
	$("select[name=\'sosuat'.$i.'\']").change(function(){
		var v = $("select[name=\'sosuat'.$i.'\'] option:selected").val();
		if(v==10) v=12;
		$("#conlai'.$i.'").val(v);
	});
	$("#giam'.$i.'").change(function(){
		if(!isNaN($("#giam'.$i.'").val())){
			$("#thanhtien'.$i.'").val(parseInt($("#gia'.$i.'").val()) * (100 - parseInt($("#giam'.$i.'").val()))/100);
		}else{
			alert("Gia tri nhap khong hop le");
			$("#giam'.$i.'").val("0");
			$("#giam'.$i.'").focus();
		}
		tinhlaiGia();
	});
	$("#gia'.$i.'").change(function(){
		if(!isNaN($("#gia'.$i.'").val())){
			$("#thanhtien'.$i.'").val(Math.round(parseInt($("#gia'.$i.'").val()) * (100 - parseInt($("#giam'.$i.'").val()))/100));
		}else{
			alert("Gia tri nhap khong hop le");
			$("#gia'.$i.'").val("0");
			$("#gia'.$i.'").focus();
		}
		tinhlaiGia();
	});
	$("#thanhtien'.$i.'").change(function(){
		if(!isNaN($("#thanhtien'.$i.'").val())){
			$("#giam'.$i.'").val(Math.round(100*((parseInt($("#gia'.$i.'").val())- parseInt($(this).val()))/parseInt($("#gia'.$i.'").val()))));
		}else{
			alert("Gia tri nhap khong hop le");
			$("#thanhtien'.$i.'").val("0");
			$("#thanhtien'.$i.'").focus();
		}
		tinhlaiGia();
	});
	</script>';
	}
	
	function getTienTipByID(){
		$ID = $this->input->post('ID');
		$result=$this->CodeGenerator_model->get( 'phieukh', '*', "ID =$ID and active=1", NULL, NULL, true );  
		if(!empty($result))
			$data['TienTip'] = $result->TienTip;
		else $data['TienTip'] = 0;
		echo json_encode($data);
		exit();
	}
	
	function _getStringAutoEE($id){
		return '<script>$( "#auto'.$id.'" )
			.bind( "keydown", function( event ) {
			if ( event.keyCode === $.ui.keyCode.TAB &&
				$( this ).data( "ui-autocomplete" ).menu.active ) {
			  event.preventDefault();
			}
		  })
			.autocomplete({
		source: "'.base_url().'transaction/searchnv",
		focus: function() {
          // prevent value inserted on focus
          //return false;
        },
		minLength: 1,
		select: function( event, ui ) {
		  $("#auto'.$id.'").val(ui.item.value);
		  $("#'.$id.'").val(ui.item.id);
		  auto = true;
          return false;		
		}
	});
	</script>
	';
	}
	
	function add_new_service(){
		$Serv_Name = $this->input->post('Serv_Name');
		$dm_id = $this->input->post('dm_id');
		$Time = $this->input->post('Time');
		$Price = $this->input->post('Price');
		$Percent_Serv = $this->input->post('Percent_Serv');
		$TienTip = $this->input->post('TienTip');
		$Name = $this->input->post('Name');
		$Serv_ID="SV_".uniqid();
		$data = array(
					'Serv_ID' => $Serv_ID,
                    'Serv_Name' => $Serv_Name,
					'Serv_Name_EN' => "",
					'Time' => $Time,
					'Cat_ID' => $dm_id,
					'Price' => $Price,
					'TienTip' => $TienTip,
					'Percent_Serv' => $Percent_Serv,
					'Create_Dt' => time()
            );
        $result = $this->CodeGenerator_model->add( 'services', $data, 'Serv_ID' );
		$data['Name'] = $Name."-".$Serv_Name." ".$Time;
		echo json_encode($data);
		exit;
	}
	
	function add_new_customer(){
		$F_Name = $this->input->post('F_Name');
		$L_Name = $this->input->post('L_Name');
		$DOB = $this->input->post('DOB');
		$Phone_NO = $this->input->post('Phone_NO');
		$Cust_ID="CC_".uniqid();
		$data = array(
						'Cust_ID' =>$Cust_ID,
						'F_Name' => $F_Name,
						'L_Name' => $L_Name,
						'DOB' =>$DOB,
						'Phone_NO' => $Phone_NO,			
						'Create_Dt' => time()
				);
		$result = $this->CodeGenerator_model->add( 'customer', $data, 'Cust_ID' );
		echo json_encode($data);
		exit;
	}
	
	function add_new_cmt(){
		$comment = $this->input->post('comment');
		$tran_id = $this->input->post('tran_id');
		$cust_id = $this->input->post('cust_id');
		$time=time();
		if(empty($tran_id)){ //chua thuc hien giao dich
			$data = array(
						'Cust_ID' => $cust_id,
						'Bonus' => 0,
						'Price' => 0,
						'Discount_Percent' => 0,
						'Create_Dt' => $time,
						'Money' => 0,
						'Completed' => -1 //chua co dich vu
			  );
				
			 $tran_id = $this->CodeGenerator_model->add( 'transaction', $data, 'Tran_ID' ,true);
		}
		
		$cmt_id = 0;
		$data = array(
						'Tran_ID'=>$tran_id,
						'Comment'=>$comment,
						'EE_ID' => $this->session->userdata('username'),
						'Create_Dt' => time()
				);
		$cmt_id = $this->CodeGenerator_model->add( 'comments', $data, 'ID',true );
		$data['html'] = '<tr id="cmt_'.$cmt_id.'">
							<td>'.date('d/m',$time).'</td>
							<td><span title="'.$comment.'">'.cat_chuoi($comment,35).'</span></td>
							<td>'.anchor( '#', 'x','class="preventDefault" title="Xoa" onclick="return deleteCmt('.$cmt_id.');"').'</td>
						</tr>';
		echo json_encode($data);
		exit;
	}
	
	function getPromotion(){
		$serv_id = $this->input->post('serv_id');
		$is_phieu = $this->input->post('is_phieu');
		$box_service_id = $this->input->post('box_service_id');
		//$serv_id = "SV_512ec6532abd4";
		$time = time();
		$data['conlai'] = 0;
		$service   =   $this->CodeGenerator_model->get( 'services', 'Price,TienTip,Percent_Serv', 'Serv_ID = "' . $serv_id . '"', NULL, NULL, true );  
		if(!$is_phieu){ //ko fai phieu'
			$sql = "select p.* from promotion as p where (p.Serv_ID1 = '$serv_id' or p.Serv_ID2 = '$serv_id' or p.Serv_ID3 = '$serv_id') AND p.Eff_Dt < $time AND p.Exp_Dt > $time";
			$result   =   $this->CodeGenerator_model->custom_query($sql, "array");
			
			if(!empty($result)) {
				$data['Promo_ID']= $result[0]['Promo_ID'];
				if($result[0]['Serv_ID1'] == $serv_id) $data['Discount_Percent']= $result[0]['Discount_Percent1'];
				if($result[0]['Serv_ID2'] == $serv_id) $data['Discount_Percent']= $result[0]['Discount_Percent2'];
				if($result[0]['Serv_ID3'] == $serv_id) $data['Discount_Percent']= $result[0]['Discount_Percent3'];
				$data['Price']= ($service->Price * (100-$data['Discount_Percent'])/100);
			}else{
				$data['Promo_ID']= "";
				$data['Discount_Percent']= 0;
				$data['Price']= $service->Price;
			}
			$data['stt']=str_replace("Serv_ID","",$serv_id);
			$data['Money']= $service->Price;
			$data['TienTip']= $service->TienTip;
			$data['Percent_Serv']= $service->Percent_Serv;
			$data['Serv_ID']= $serv_id;
		}else{//neu la phieu
			$sql = "select p.ID, p.SoSuat, p.Tang, p.TienTip, p.Conlai, p.Gia from phieukh as p, services as s where p.Serv_ID = s.Serv_ID and ID = $box_service_id and p.Active = 1";
			$tientip   =   $this->CodeGenerator_model->custom_query($sql,"array");  
			if(!empty($tientip)){ //la phieu da co dich vu
				if($tientip[0]['Conlai'] == 12 || $tientip[0]['Conlai'] == 6){ //cvua 
					
				}				
			}else{ //phieu chua co dich vu
				$sql = "select t.ID, s.SoSuat, s.Tang, s.TienTip, s.Price from tientip as t, services as s where t.Serv_ID = s.Serv_ID and ID = $box_service_id";
				$tientip   =   $this->CodeGenerator_model->custom_query($sql,"array");  
			}
			$data['Money']= $service->Price * $tientip[0]['SoSuat'];
			$data['TienTip']= $service->TienTip;
			$data['Percent_Serv']= $service->Percent_Serv;
			$data['Price']= $service->Price * $tientip[0]['SoSuat'];//thanh tien
			$data['Discount_Percent']= 0;
			$data['Serv_ID']= $serv_id;
			$data['conlai'] = $tientip[0]['SoSuat'] + $tientip[0]['Tang'];
			$is_phieu = 1;
		}
		$data['is_phieu'] = $is_phieu;	
		$currency = "vnd";
		if($currency == "vnd"){
			$data['Money'] = $data['Money']*1000;
			$data['Price'] = $data['Price']*1000;
			$data['TienTip'] = $data['TienTip']*1000;
		}
		echo json_encode($data);
		exit;
	}
	
	function search(){
		$term = $this->input->get('term');
		// $tmp = explode(", ",$term);
		// if(count($tmp)>0) $term = $tmp[count($tmp)-1];
		$sql = "select Cust_ID as id, CONCAT(F_Name, ' ' , L_Name, ' (',Phone_NO,')') as label, CONCAT(F_Name, ' ' , L_Name) as value from customer where F_Name like '%$term%' or L_Name like '%$term%'";
		$results = $this->CodeGenerator_model->custom_query($sql, "array");
		echo json_encode($results);
		exit();
	}
	
	function updateItem(){
		$value= $this->input->post("value");
		$rel= $this->input->post("rel");
		$id_change= $this->input->post("id_change");
		$arr = explode(",",$rel);
		$result = $this->CodeGenerator_model->edit($arr[0], array($arr[3]=>$value), '', '',array($arr[1]=>$arr[2]) );
		 $data['result'] = $result;
		// $data['result'] = true;
		if(isset($arr[4]) && $arr[4])
			$data['value'] = formatcurrency($value * 1000);
		else if(isset($arr[5]) && $arr[5]) $data['value'] = $arr[5];
		else if(isset($arr[6]) && $arr[6] ) $data['value'] = str_replace("[value]",$value,$arr[6]);
		else $data['value'] = $value;
		$data['id_change'] = $id_change;
		echo json_encode($data);
		exit;
	}
	
	function searchnv(){
		$term = $this->input->get('term');
		$tmp = explode(", ",$term);
		if(count($tmp)>0) $term = $tmp[count($tmp)-1];
		$sql = "select EE_ID as id, Name as label, Name as value from employee where (Personal_ID like '%$term%' or Name like '%$term%') and role!=".ADMINISTRATOR. " and role =".EMPLOYER." and Name !='test'";
		$results = $this->CodeGenerator_model->custom_query($sql, "array");
		// echo json_encode($results);
		echo json_encode($results);
		exit();
	}

	function manage( ){
		$this->load_template();
		$filter = $this->input->get('filter');
		$orderby = $this->input->get('orderby');
		$time = $this->input->get('time');
		if(empty($time))
			$time=$this->input->post('transaction_dt');
		if(empty($time))
			$time = date("d/m/Y H:i:s",time());
		$this->data['time'] = $time;
		
		$limit = $this->getLimit("D",$time);
		//paging
        $config['base_url'] = base_url().'transaction/manage/';
		$config['suffix']="";
		if($filter) {
			$config['suffix'] = "/?filter=$filter&orderby=$orderby&time=$time";
			$config['first_url'] = $config['base_url']."0/?filter=$filter&orderby=$orderby&time=$time";
		}
		if(empty($config['suffix'])){
			$config['suffix'] = "/?time=$time";
			$config['first_url'] = $config['base_url']."0/?time=$time";
		}
		$sql = "select count(Tran_ID) as total from transaction where Create_Dt >= ".$limit['datemin']." AND Create_Dt <= ".$limit['datemax'];
		$total = $this->CodeGenerator_model->custom_query($sql,"array");
		if(!empty($total)) $config['total_rows'] = $total[0]['total'];
		else $config['total_rows'] = 0;
        // $config['total_rows'] = $this->CodeGenerator_model->count('transaction');
        $config['per_page'] = PER_PAGE;	
        $this->pagination->initialize($config); 

		$start = $this->uri->segment(3);
		if(empty($start)) $start = 0;
		$perpage = $config['per_page'];
        // Get rules from config file
        // --------------------------------------------------
        //$rules                  =   $this->form_validation->_config_rules[ 'transaction_add' ];
        $rules                  =         array(array('field_id' => 'stt','label' => 'stt','control' => 'auto','class'=>'first border-right','width'=>'5%','style'=>'border-right: solid 3px #fff;'),
		array('field_id' => 'khachhang','label' => 'Khách hàng','control' => 'string','class'=>'border-right','width'=>'10%','style'=>'border-right: solid 3px #fff;'),
		array('field_id' => 'Serv_FullName','label' => 'Dịch vụ','control' => 'Array','order'=>false,'class'=>'border-right','width'=>'30%','style'=>'border-right: solid 3px #fff;'),
		array('field_id' => 'Price','label' => 'Giá trị dịch vụ','control' => 'vnd','isedit'=>false,'rel'=>'transaction,Tran_ID,[value],Price,1','class'=>'border-right','width'=>'15%','style'=>'border-right: solid 3px #fff;'),
		array('field_id' => 'EE_Name','label' => 'Tips','control' => 'string','class'=>'border-right','width'=>'9%','style'=>'border-right: solid 3px #fff;'),
		array('field_id' => 'Price_Serv','label' => '%<br/>Dịch Vụ','control' => 'string','class'=>'border-right','width'=>'9%','style'=>'border-right: solid 3px #fff;'),
		array('field_id' => 'Discount_Percent','label' => 'KM','control' => 'Array','isedit'=>false,'rel'=>'transaction,Tran_ID,[value],Discount_Percent,0','class'=>'border-right','width'=>'9%','style'=>'border-right: solid 3px #fff;'),
		array('field_id' => 'Money','label' => 'Còn lại','control' => 'vnd','isedit'=>false,'rel'=>'transaction,Tran_ID,[value],Money,1','class'=>'border-right','width'=>'9%','style'=>'border-right: solid 3px #fff;'));
       
		
		if(empty($filter)) $str_orderby = 'order by Tran_ID DESC'; else $str_orderby = "order by $filter $orderby";
		$sql = "select t.*, CONCAT(c.F_Name, ' ' , c.L_Name) as khachhang, p.SoSuat, p.Conlai,p.Tang from customer as c, transaction as t left join phieukh as p on t.Phieu_ID=p.ID where c.Cust_ID = t.Cust_ID and t.Create_Dt >= ".$limit['datemin']." AND t.Create_Dt <= ".$limit['datemax']." $str_orderby Limit $start,$perpage";
       
		 // Make header
        // --------------------------------------------------
        $header = array( );
        foreach( $rules as $k => $item ){
            $header[ ] = $item[ 'label' ];
			$str1='';$str2='';
			if($filter == $item['field_id']){
				if($orderby == "DESC") {$orderby = "ASC";$img1="display: none;";$img2="display: inline;"; } else {$orderby = "DESC";$img1="display: inline;";$img2="display: none;";}
				$url= base_url()."transaction/manage/$start/?filter=$filter&orderby=$orderby&time=$time";
				$str1 = 'onmouseout="$(\'.soimg2\').toggle()" onmouseover="$(\'.soimg2\').toggle()"';
				$str2='<img class="icon ic_s_asc soimg2" alt="Ascending" title="" src="'.base_url().'resources/images/dot.gif" style="'.$img1.'"> <img class="icon ic_s_desc soimg2 hide" alt="Descending" title="" src="'.base_url().'resources/images/dot.gif" style="'.$img2.'">';
			}else $url= base_url()."transaction/manage/$start/?filter=".$item['field_id']."&orderby=ASC&time=$time";
			$rules[$k]['html'] ='<span><a title="" '.$str1.' href="'.$url.'">'.$item[ 'label' ].' '.$str2.'</a></span>';
			if(isset($item['order'])&&!$item['order']) $rules[$k]['html'] = $item[ 'label' ];
        }
		$this->data[ 'rules' ]  =   $rules;
		
        $this->data[ 'header' ] =   $header;
	   
        $results=$this->CodeGenerator_model->custom_query($sql,"array");
        // Make action Edit/Delete
        // --------------------------------------------------
        for( $i = 0; $i < count( $results ); $i++ ){
	       $id = array_values( $results[ $i ]);
		   $Tran_ID = $results[$i]['Tran_ID'];
		   //duyet service va nguoi duoc tip
		     $str_dv = "";
			 $str_nguoitip = "";
		   $sql = "select s.Serv_Name, ca.Name, e.Personal_ID, e.Name as e_Name,tt.Price,tt.Price_Serv,tt.ID  from services as s, categories as ca, employee as e, tientip as tt where tt.Tran_ID='$Tran_ID' AND s.Cat_ID = ca.Ca_ID and e.EE_ID = tt.EE_ID and tt.Serv_ID = s.Serv_ID";
		   // echo $sql;die;
		   $services = $this->CodeGenerator_model->custom_query($sql,"array");
		   $tiendv = "";
		   foreach($services as $i=> $t){
				$duynhat1 =  uniqid();
				$duynhat2 =  uniqid();
				$str_dv .=$t['Serv_Name']."(".$t['Name'].")"." + ";
				 $str_nguoitip .= '<span class="doubleclick" id="pibien'.$duynhat1.'" rel="'.$duynhat1.'">'.$t['e_Name'].'</span>'.'<input rel="auto" class="edit" style="display:none;" value="'.$t['e_Name'].'" type="text" id="auto'.$duynhat1.'" />'.'<input id="'.$duynhat1.'" type="hidden" rel="tientip,ID,'.$t['ID'].',EE_ID" value="'.$t['Personal_ID'].'" />'.$this->_getStringAutoEE($duynhat1).'<span class="doubleclick" id="pibien'.$duynhat2.'" rel="'.$duynhat2.'">'.'('.$t['Price'].'k)</span>'.'<input class="edit" style="display:none;" value="'.$t['Price'].'" type="text" rel="tientip,ID,'.$t['ID'].',Price,0,0,([value]k)" id="'.$duynhat2.'" /><br/>';
				$tiendv .= $t['e_Name']."(".$t['Price_Serv']."k)<br/>";
		   }  
		   
		   $sql = "select s.Serv_Name, ca.Name, e.Personal_ID, e.Name as e_Name, p.TienTip,p.SoSuat, p.Conlai,p.Price_Serv from services as s, categories as ca, employee as e, phieukh as p where p.Tran_ID='$Tran_ID' and p.EE_ID = e.EE_ID and s.Cat_ID = ca.Ca_ID and p.Serv_ID = s.Serv_ID";
		   $phieus = $this->CodeGenerator_model->custom_query($sql,"array");
		   foreach($phieus as $t){
				$str_dv .="Phieu ".$t['SoSuat']." suat - con lai ".$t['Conlai']." suat - ".$t['Serv_Name']."(".$t['Name'].")"." + ";
				$str_nguoitip .= $t['Personal_ID']."(".$t['TienTip']."k), ";
				$tiendv .=$t['e_Name']."(".$t['Price_Serv']."k)";
		   }
		   $results[$i]['stt'] =$i+1;
		   $results[$i]['Serv_FullName'] = substr($str_dv, 0, -3);
		   $results[$i]['EE_Name'] = "<span style='float:left;width:70px;'>".substr($str_nguoitip,0,-2)."</span>";
		   $results[$i]['Price_Serv'] = $tiendv;
            $results[ $i ][ 'Edit'   ]   =  anchor( base_url( ) . 'transaction/edit/' . $id[ 0 ], 'Edit');  
            $results[ $i ][ 'Delete' ]   =  anchor( 
                        base_url( ) . 'index.php/transaction/delete/' . $id[ 0 ], 
                        'Del',
                        array( 'onClick' => 'return deletechecked(\' ' . base_url() . 'transaction/delete/' . $id[ 0 ] . ' \')' ) );  
        }		
        $this->data[ 'results'        ]     =   $results;
        $this->data[ 'master_limited' ]     =   explode(',', 'stt,Tran_ID,Cust_ID,SoSuat,Conlai,Serv_FullName,EE_Name,Bonus,khachhang,Serv_ID,Promo_ID,Price,Discount_Percent,Create_Dt,Money,Completed,Price_Serv');
		
		//lay tien tips cho moi nhan vien
		
		$sql = "select EE_ID, Personal_ID,Name  from employee where role = 1 and active = 1 and Personal_ID!='test' and Name!='test'";
		$results = $this->CodeGenerator_model->custom_query($sql,"array");
		$sum_dv = 0;
		foreach($results as $k=> $item){
			$ee_id = $item['EE_ID'];	
			$price_serv = 0;
			$sql = "select sum(tt.Price) as total from tientip as tt where tt.EE_ID='$ee_id' and tt.Create_Dt >= ".$limit['datemin']." AND tt.Create_Dt <= ".$limit['datemax']."";
			$result = $this->CodeGenerator_model->custom_query($sql,"array");
			if(!empty($result)) $price_serv +=$result[0]['total'];
			$sql = "select sum(p.TienTip) as total from phieukh as p where p.EE_ID='$ee_id' and p.Create_Dt >= ".$limit['datemin']." AND p.Create_Dt <= ".$limit['datemax']."";
			$result = $this->CodeGenerator_model->custom_query($sql,"array");
			if(!empty($result)) $price_serv +=$result[0]['total'];
			$sum_dv +=$price_serv;
			$results[$k]['Price'] = $price_serv;
		}
		$this->data['tientips'] = $results;
		//kh cu
		$this->data['khcu'] = $this->getKHCu($limit['datemin'],$limit['datemax']);
		//so kh
		$this->data['khtc'] = $this->getKH($limit['datemin'],$limit['datemax']);
		//kh moi
		$this->data['khmoi'] = $this->data['khtc'] - $this->data['khcu'];
		
		//phieu cu
		$sql = "select count(ID) as total from phieukh where gia=0 and ((sosuat=5 and conlai < 5) or (sosuat=10 and conlai < 12)) and Create_Dt >= ".$limit['datemin']." AND Create_Dt <= ".$limit['datemax'];
		$total = $this->CodeGenerator_model->custom_query($sql,"array");
		$this->data['phieucu'] = $total[0]['total'];
		//phieu moi
		$sql = "select count(ID) as total from phieukh where gia >0 and ((sosuat=5 and conlai = 5) or (sosuat=10 and conlai = 12)) and Create_Dt >= ".$limit['datemin']." AND Create_Dt <= ".$limit['datemax'];
		$total = $this->CodeGenerator_model->custom_query($sql,"array");
		$this->data['phieumoi'] = $total[0]['total'];
		//tien mat
		$sql = "select sum(Price) as total from transaction where Create_Dt >= ".$limit['datemin']." AND Create_Dt <= ".$limit['datemax'];
		$total = $this->CodeGenerator_model->custom_query($sql,"array");
		$this->data['tienmat'] = $total[0]['total'];
		//tien tips
		$this->data['tientip'] = $this->getTienTip($limit['datemin'],$limit['datemax']);
		//% service
		$this->data['percent_service'] = $this->getPercentService($limit['datemin'],$limit['datemax']);
		//tong
		$this->data['tongket'] = $this->data['tienmat'] - $this->data['tientip'] - $this->data['percent_service'];
		
	   //die;
       $this->data[ 'action'         ]     =   array(array('id' => 'new','label' => 'Giao dich moi','url' => 'index.php/transaction/',),array('id' => 'delete','label' => 'Delete','url' => '',),);
        // $this->load->view( 'transaction_list', $this->data ); 
		$this->template->write( 'title', 'Spa - Giao dich' );
        $this->template->write_view( 'content', 'transaction_list.php',$this->data );
        $this->template->render();
    }
	
	function chitietthanhtoan( ){
		$this->load_template();
        $this->data[ 'custom_error' ] = '';
		$username = "noname";
		$userid = 0;
		$Cust_ID =  $this->input->get('Cust_ID');
		$goto=false;
		if(empty($Cust_ID))
			$Cust_ID = $this->input->post('Cust_ID');
		else $goto = true;
        
        if( $this->form_validation->run( 'transaction_edit' ) == false ){
            $this->data[ 'custom_error' ] = ( validation_errors( ) ? '<div class="form_error">' . validation_errors( ) . '</div>' : false );

        }else{                            
            $data = array(
                'Personal_ID' => $this->input->post('Personal_ID'),
					'Promo_ID' => $this->input->post('Promo_ID'),
					'Create_Dt' => $this->input->post('Create_Dt'),
					'Money' => $this->input->post('Money'),
					'Completed' => $this->input->post('Completed')
            );
			if( $this->CodeGenerator_model->edit( 'transaction', $data, 'Tran_ID', $this->input->post( 'Tran_ID' ) ) == TRUE ){
				redirect( base_url( ) . 'index.php/transaction/manage/' );
			}else{
				$this->data[ 'custom_error' ] = '<div class="form_error"><p>An Error Occured</p></div>';
			}
		}
		if(empty($Cust_ID))
			$result   =   $this->CodeGenerator_model->get( 'transaction', '*', 'Tran_ID = "' . $this->uri->segment( 3 ) . '"', NULL, NULL, true );  
		else {//lay giao dich chua thuc hien buoc thanh toan
			
			$result   =   $this->CodeGenerator_model->get( 'transaction', '*', 'Cust_ID = "' . $Cust_ID . '" AND Completed=0', NULL, NULL, true,'Create_Dt DESC' );  
		}
		//get services cua 1 transaction
		if(!empty($result))
			$Tran_ID = $result->Tran_ID;
		else $Tran_ID=0;
			// + dich vu
		$sql = "select tt.ID,s.Serv_Name, ca.Name, e.Personal_ID, e.Name as e_Name,tt.Price as TienTip,tt.Price_Serv,tt.ID,s.Price as Gia, tt.Giam,tt.GhiChu from services as s, categories as ca, employee as e, tientip as tt where tt.Tran_ID='$Tran_ID' AND s.Cat_ID = ca.Ca_ID and e.EE_ID = tt.EE_ID and tt.Serv_ID = s.Serv_ID";
		 // echo $sql;die;
		 $services = $this->CodeGenerator_model->custom_query($sql,"array");
		 foreach($services as $k => $item){
			$services[$k]['SoSuat'] = "";			
			$services[$k]['Conlai'] = "";		
			$services[$k]['Serv_Full'] = $item['Serv_Name']."(".$item['Name'].")";		
		 }
		// + phieu
		$sql = "select p.ID, s.Serv_Name, ca.Name, e.Personal_ID, e.Name as e_Name, p.TienTip,p.SoSuat, p.Conlai,p.Price_Serv,p.Gia, p.Giam,p.GhiChu  from services as s, categories as ca, employee as e, phieukh as p where p.Tran_ID='$Tran_ID' and p.EE_ID = e.EE_ID and s.Cat_ID = ca.Ca_ID and p.Serv_ID = s.Serv_ID and p.Active = 1";
		 $phieus = $this->CodeGenerator_model->custom_query($sql,"array");
		 foreach($phieus as $k=>$t){
			$phieus[$k]["Serv_Full"] = "Phieu ".$t['SoSuat']." suat - con lai ".$t['Conlai']." suat - ".$t['Serv_Name']."(".$t['Name'].")";
		 }
		 $services = array_merge($services, $phieus);
		 
		 //dich vu vip
		 $sql = "select s.Serv_Name, ca.Name, tt.Serv_ID,tt.ID, tt.Price as TienTip, tt.Giam, s.Price from tientip as tt, services as s,categories as ca where tt.Tran_ID='$Tran_ID' and tt.Vip=1 and s.Cat_ID = ca.Ca_ID and tt.Serv_ID = s.Serv_ID";
		 $services_vip = $this->CodeGenerator_model->custom_query($sql,"array");
		  foreach($services_vip as $i=> $t){
				$sql = "select tv.*, e.Personal_ID, e.Name as e_Name,s.Serv_Name, ca.Name,e.EE_ID from transaction_vip as tv, employee as e,categories as ca, services as s where e.EE_ID=tv.EE_ID and tv.TienTip_ID='".$t['ID']."' AND s.Cat_ID = ca.Ca_ID and tv.Serv_ID = s.Serv_ID";
				$child=$this->CodeGenerator_model->custom_query($sql,"array");
				$services_vip[$i]['child'] = $child;
				$services_vip[$i]['giam'] = $child;
		  }
		  //end dich vu vip
		 
		 //get info customer
		 $customer = null;
		 if(!empty($result))
		 $customer =  $this->CodeGenerator_model->get( 'customer', '*', 'Cust_ID = "' . $result->Cust_ID . '"', NULL, NULL, true );		 

		 //print_r($services);
		$this->data['result'] = $result;
		
		$this->data['services_vip'] = $services_vip;
		$this->data['services'] = $services;
		$this->data['customer'] = $customer;
		
		// $this->load->view( 'transaction_edit', $this->data );		
		$this->template->write( 'title', 'Chi tiet thanh toán' );
        $this->template->write_view( 'content', 'chitietthanhtoan.php',$this->data );
        $this->template->render();
    }
	
	function delete( ){
        $ID =  $this->uri->segment( 3 );        
		
		$result=$this->CodeGenerator_model->get( 'phieukh', '*', "Tran_ID =$ID and active=1", NULL, NULL, true ); 
		$this->CodeGenerator_model->delete(  'transaction', 'Tran_ID', $ID );		
		//get tientip
		$results = $this->CodeGenerator_model->custom_query("select ID from tientip where Tran_ID = $ID","array");
		foreach($results as $item){
			$this->CodeGenerator_model->delete(  'transaction_vip', 'TienTip_ID', $item['ID'] );             
		}
        $this->CodeGenerator_model->delete(  'tientip', 'Tran_ID', $ID );             
        $this->CodeGenerator_model->delete(  'phieukh', 'Tran_ID', $ID );             
        redirect( base_url( ) . 'transaction/giaodich/' );
    }   
	//xoa ghi chu
	function del_cmt(){
		$id= $this->input->post("id");
		echo $this->CodeGenerator_model->delete(  'comments', 'ID', $id );		
		exit();
	}
	
	function strService(){
		$selected = $this->input->post("Serv_ID");
		$data['cb_services'] = $this->str_services($selected);
		echo json_encode($data);
		exit();
	}
	
	function str_services($selected){
		$sql = "select s.*, c.Name as Category_Name from services as s, categories as c where s.Cat_ID=c.Ca_ID AND s.SoSuat=1";
		$categories   =   $this->CodeGenerator_model->custom_query($sql, "array");
		$combobox_cats=array();
		$combobox_cats[""]="---  Chon dich vu ----";
		foreach($categories as $cat){
			$combobox_cats[$cat['Serv_ID']]=$cat['Category_Name']."-".$cat['Serv_Name'];
		}
		return form_dropdown('Serv_ID', $combobox_cats,$selected,"onchange='return service_change(\"Serv_ID\");'");
	}
	
	function getService(){
		$rel = $this->input->post('rel');
		$arr= explode(",",$rel);
		
			// + dich vu
		if(!$arr[0]){
			$boolNewBox = 1;
			$sql = "select tt.ID,s.Serv_Name, ca.Name, e.Personal_ID,e.EE_ID, e.Name as e_Name,tt.Price as TienTip,tt.Price_Serv,tt.ID,s.Price as Gia, tt.Giam,tt.GhiChu, tt.Serv_ID,tt.Tran_ID,s.Percent_Serv,s.SoSuat,s.Tang from services as s, categories as ca, employee as e, tientip as tt where tt.ID=".$arr[1]." and s.Cat_ID = ca.Ca_ID and e.EE_ID = tt.EE_ID and tt.Serv_ID = s.Serv_ID";
			 // echo $sql;die;
			 $services = $this->CodeGenerator_model->custom_query($sql,"array");
			 foreach($services as $k => $item){
				//$services[$k]['SoSuat'] = "";			
				$services[$k]['Conlai'] = "";		
				$services[$k]['Serv_Full'] = $item['Serv_Name']."(".$item['Name'].")";		
			 }
		 }else{ //lan dau tien se ko zo day
		// + phieu
			$boolNewBox = 0;
			$sql = "select p.ID, s.Serv_Name, ca.Name, e.Personal_ID,e.EE_ID, e.Name as e_Name, p.TienTip,p.SoSuat, p.Conlai,p.Price_Serv,p.Gia, p.Giam,p.GhiChu,p.Serv_ID,p.Tran_ID,s.Percent_Serv, p.Tang, p.Saved from services as s, categories as ca, employee as e, phieukh as p where p.ID=".$arr[1]." and p.EE_ID = e.EE_ID and s.Cat_ID = ca.Ca_ID and p.Serv_ID = s.Serv_ID";
			 $services = $this->CodeGenerator_model->custom_query($sql,"array");
			 foreach($services as $k=>$t){
				$services[$k]["Serv_Full"] = "Phieu ".$t['SoSuat']." suat - con lai ".$t['Conlai']." suat - ".$t['Serv_Name']."(".$t['Name'].")";
			 }
		 }
		 $data = array();
		 if(!empty($services)) {
			$data=$services[0];
			$data['phieu'] = $arr[0];
			$data['box_new'] = 0;
			if($data['SoSuat'] > 1){ //su dung phieu
				$data['box_new'] = $boolNewBox;
				$data['phieu'] = 1;
			}
			// service
			$sql = "select s.*, c.Name as Category_Name from services as s, categories as c where s.Cat_ID=c.Ca_ID and s.SoSuat = 1";
			$categories   =   $this->CodeGenerator_model->custom_query($sql, "array");
			$combobox_cats=array();
			foreach($categories as $cat){
				$combobox_cats[$cat['Serv_ID']]=$cat['Category_Name']."-".$cat['Serv_Name'];
			}
			$data['cb_services']=$this->str_services($data['Serv_ID']);
		 }
		 $data['Vip'] = 0;
		 $data['vipchild'] = 0;
		 $data['vipid'] = 0;
		 $data['TienTip'] = $data['TienTip']*1000;
		 $data['Gia'] = $data['Gia']*1000;
		 $data['thanhtien'] = $data['Gia']*1000;
		 echo json_encode($data);
		 exit();
	}
	
	function getServicesVip(){
		$rel = $this->input->post('rel');
		$arr= explode(",",$rel);		
		if($arr[0]==2){ //lay dich vu VIP
			$sql = "select s.Serv_Name, ca.Name, tt.Price as TienTip ,tt.Price_Serv,tt.ID,s.Price as Gia, tt.Giam,tt.GhiChu, tt.Serv_ID,tt.Tran_ID,s.Percent_Serv,s.SoSuat,s.Tang from services as s, categories as ca, tientip as tt, employee as e where s.Cat_ID = ca.Ca_ID and tt.Serv_ID = s.Serv_ID and tt.ID='".$arr[1]."'";
			 $services = $this->CodeGenerator_model->custom_query($sql,"array");
		   $data['vipchild'] = 0;
		}else{ //dich vu con VIP
			$sql = "select s.Serv_Name, ca.Name, e.Personal_ID,e.EE_ID, e.Name as e_Name, tv.Price as TienTip ,tv.Price_Serv,tv.ID,s.Price as Gia, tv.Giam, tv.Serv_ID, s.Percent_Serv,s.SoSuat,s.Tang from services as s, categories as ca, transaction_vip as tv, employee as e where s.Cat_ID = ca.Ca_ID and tv.EE_ID = e.EE_ID and tv.Serv_ID = s.Serv_ID and tv.ID='".$arr[1]."'";
			 $services = $this->CodeGenerator_model->custom_query($sql,"array");
			 $data['vipchild'] = 1;
		}
		 // service
		if(!empty($services)) {
			$data=array_merge($services[0],$data);
			$data['phieu'] = 0;
			$data['box_new'] = 0;
			$data['vipid'] = $data['ID'];
			// service
			$sql = "select s.*, c.Name as Category_Name from services as s, categories as c where s.Cat_ID=c.Ca_ID and s.SoSuat = 1";
			$categories   =   $this->CodeGenerator_model->custom_query($sql, "array");
			$combobox_cats=array();
			foreach($categories as $cat){
				$combobox_cats[$cat['Serv_ID']]=$cat['Category_Name']."-".$cat['Serv_Name'];
			}
			$data['cb_services']=$this->str_services($data['Serv_ID']);
		 }
		 $data['Vip'] =1;
		 $currency = "vnd";
		 if($currency == "vnd"){
			$data['thanhtien'] = ($data['Gia'] * (100 - $data['Giam'])/100)*1000;
			$data['TienTip'] = $data['TienTip']*1000;
			$data['Gia'] = $data['Gia']*1000;
		 }

		 echo json_encode($data);
		 exit();
	}
	
	
	function gethistory(){
		$Cust_ID = $this->input->post('cust_id');
		if(empty($Cust_ID))
			$data['html'] ="";
		else {//lay giao dich gan nhat
			//lay giao dich có sử dụng phiếu con hieu luc
			$sql = "Select p.Tran_ID, p.Serv_ID from phieukh as p where p.Cust_ID ='$Cust_ID' and p.Off = 0 GROUP BY p.Tran_ID order by Create_Dt desc";
			
			$phieutontai = $this->CodeGenerator_model->custom_query($sql,"array");
			
			$result   =   $this->CodeGenerator_model->get( 'transaction', '*', 'Cust_ID = "' . $Cust_ID . '"', NULL, NULL, true,'','Create_Dt DESC' );  
			//get services cua 1 transaction
			if(!empty($result))
				$Tran_ID = $result->Tran_ID;
			else $Tran_ID=0;
			$html="";
				// + dich vu
			$sql = "select tt.ID,s.Serv_Name, ca.Name, e.Personal_ID, e.Name as e_Name,tt.Price as TienTip,tt.Price_Serv,tt.ID,s.Price as Gia, tt.Giam,tt.GhiChu, tt.Serv_ID, e.EE_ID from services as s, categories as ca, employee as e, tientip as tt where tt.Tran_ID='$Tran_ID' AND s.Cat_ID = ca.Ca_ID and e.EE_ID = tt.EE_ID and tt.Serv_ID = s.Serv_ID";
			 $services = $this->CodeGenerator_model->custom_query($sql,"array");
			 foreach($services as $k => $item){
				$services[$k]['Serv_Full'] = $item['Serv_Name']."(".$item['Name'].")";	
				$services[$k]['ID'] = "";	
				$html .= '<div class="parent"><div class="item service shadow"><span title="'.$services[$k]['Serv_Full'].'">'.cat_chuoi($services[$k]['Serv_Full'],20).'</span></div><hr/> <div class="item nhanvien nhapnhay shadow'.$k.'" rel="#chitiet3 .nhapnhay'.$k.'"><span>'.$services[$k]['e_Name'].'</span></div><hr/><div class="item descr shadow"><span>Mô tả</span></div><a class="remove" href="javascript:" title="Remove ">x</a><input type="hidden" name="service" value="'.$services[$k]['Serv_ID'].'" /><input type="hidden" name="nhanvien" value="'.$services[$k]['EE_ID'].'" /><input type="hidden" name="xldichvu" value="0" /><input type="hidden" name="phieu" value="" /></div>';				
			 }
			  //dich vu vip
		 $sql = "select tt.Serv_ID,tt.ID,s.Serv_Name, ca.Name from tientip as tt, services as s,categories as ca where s.Serv_ID = tt.Serv_ID and tt.Tran_ID='$Tran_ID' and tt.Vip=1 AND s.Cat_ID = ca.Ca_ID";
		 $services_vip = $this->CodeGenerator_model->custom_query($sql,"array");
		  foreach($services_vip as $i=> $t){
				$sql = "select e.Personal_ID, e.Name as e_Name,tv.Price,tv.ID,s.Serv_Name, ca.Name,tv.Serv_ID,e.EE_ID from transaction_vip as tv, employee as e,categories as ca, services as s where e.EE_ID=tv.EE_ID and tv.TienTip_ID='".$t['ID']."' AND s.Cat_ID = ca.Ca_ID and tv.Serv_ID = s.Serv_ID";
				$child=$this->CodeGenerator_model->custom_query($sql,"array");
				$services_vip[$i]['child'] = $child;
		  }
		   foreach($services_vip as $i=> $t){
			  $html .= '<div class="parent_group"><span style="width: 300px;font-weight:bold;color:#cfa62b;">'.$t['Serv_Name'].'-'.$t['Name'].'</span><a title="Remove " href="javascript:" style="position: relative; top: -3px; right: 1px;" class="remove">x</a>';
				foreach($t['child'] as $k => $item){
					$full_name = $item['Serv_Name'].' - '.$item['Name'];
					$html.='<div class="parent" style="border: 1px solid transparent;"><div class="item service shadow"><span title="'.$full_name.'">'.cat_chuoi($full_name,25).'</span></div> <hr><div class="item nhanvien shadow nhapnhay'.$k.'" rel="#chitiet3 .nhapnhay'.$k.'"><span>'.$item['e_Name'].'</span></div><hr><div class="item descr shadow"><span>Mô tả</span></div><input type="hidden" value="'.$item['Serv_ID'].'" name="service"><input type="hidden" value="'.$item['EE_ID'].'" name="nhanvien"><input type="hidden" value="0" name="xldichvu"><input type="hidden" value="" name="phieu"></div>';
				}
			 $html .='<input type="hidden" value="'.$t['Serv_ID'].'" name="service_vip_id"><input type="hidden" value="0" name="xldichvu_parent"></div>';
		}
		  //end dich vu vip
			// + phieu
			$str_in = "(";
			$arr_in = array();
			foreach($phieutontai as $itm){
				if(!in_array($itm['Serv_ID'],$arr_in)){
					$arr_in[] = $itm['Serv_ID'];
					$str_in .="'".$itm['Tran_ID']."',";
				}
			}
			$str_in .="'".$Tran_ID."')";
			
			$sql = "select p.ID, s.Serv_Name, ca.Name, e.Personal_ID, e.Name as e_Name, p.TienTip,p.SoSuat, p.Conlai,p.Price_Serv,p.Gia, p.Giam,p.GhiChu, p.Serv_ID, e.EE_ID, p.Tang,p.PhieuCode from services as s, categories as ca, employee as e, phieukh as p where p.Tran_ID IN $str_in and p.EE_ID = e.EE_ID and s.Cat_ID = ca.Ca_ID and p.Serv_ID = s.Serv_ID and p.Active = 1 and p.Off = 0 order by p.ID desc";
			 $phieus = $this->CodeGenerator_model->custom_query($sql,"array");
			 $arr_check = array();
			//$phieus_new = array();
			 foreach($phieus as $k=>$t){
				if(!in_array($t['PhieuCode'],$arr_check)){
					$phieus[$k]["Serv_Full"] = "Phieu ".$t['SoSuat']." suat - con lai ".$t['Conlai']." suat - ".$t['Serv_Name']."(".$t['Name'].")";
					$phieus[$k]['ID'] = "";		
					$html .= '<div class="parent"><div class="item service shadow"><span title="'.$phieus[$k]['Serv_Full'].'">'.cat_chuoi($phieus[$k]['Serv_Full'],25).'</span></div> <hr/><div class="item nhanvien shadow"><span>'.$phieus[$k]['e_Name'].'</span></div><hr/><div class="item descr shadow"><span>Mô tả</span></div><a class="remove" href="javascript:" title="Remove ">x</a><input type="hidden" name="service" value="'.$phieus[$k]['Serv_ID'].'" /><input type="hidden" name="nhanvien" value="'.$phieus[$k]['EE_ID'].'" /><input type="hidden" name="xldichvu" value="0" /><input type="hidden" name="phieu" value="'.$phieus[$k]['SoSuat'].','.$phieus[$k]['Tang'].','.$phieus[$k]['Conlai'].','.$phieus[$k]['Giam'].','.$phieus[$k]['TienTip'].','.$phieus[$k]['PhieuCode'].'" /></div>';		
					$arr_check[]=$t['PhieuCode'];
					//$phieus_new[]=$phieus[$k];
				}
			 }
			 $data['html'] = $html;
			 
		}
		echo json_encode($data);
		exit();
	}
}

/* End of file index.php */
/* Location: ./index.php */